﻿using System;
using System.Collections.Generic;
using System.Linq;
using RN.ERP.DAL.Context;
using RN.ERP.Entity;
using Newtonsoft.Json;
using Fly.Log;
using System.Configuration;
using RN.ERP.Entity.ZBDLRY;
using RN.ERP.DAL.LcDAL;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using RN.ERP.Entity.ResultModels;
using System.Data.SqlClient;
using Fly.FlyCommon;
using System.Data.Objects.SqlClient;
//using FlowCommon = Fly.Common.WorkFlow;
using Fly.Common.Linq;
using System.Data;
using RN.ERP.BLL.LC.Utilities;
using RN.ERP.DAL;

namespace RN.ERP.BLL.LC
{
    public class BasicBLL : BaseBasicBLL
    {
        private ZBDL_Context dbContext
        {
            get
            {
                return (ZBDL_Context)base.baseContext;
            }
        }

        public BasicBLL()
        {
            base.baseContext = new ZBDL_Context();
        }

        private int _appID = 97;

        private int AppID
        {
            get
            {
                int.TryParse(ConfigurationManager.AppSettings["AppId"], out _appID);
                return _appID;
            }
        }
        public override string DoLogin(string userName, string password, string userType, string systemid)
        {
            UserLoginInfo loginInfo = new UserLoginInfo();
            IList<int> roleIdCollection = GetRoleCollection(userType);
            ////查询用户表信息。
            T_Sys_Users_Zbdl user = dbContext.T_Sys_Users.SingleOrDefault(
                u =>
                u.UserName == userName &&
                u.Pwd == password &&
                u.bLocked == 0 &&
                u.bDeleted == 0 &&
                roleIdCollection.Contains((int)u.RoleID));
            T_Sys_Users userl = new T_Sys_Users();
            #region
            if (user != null)
            {
                userl.AreaCode = user.AreaCode;
                userl.DogID = user.DogID;
                userl.UserGuid = user.UserGuid;
                userl.RoleID = user.RoleID;
                userl.Name = user.Name;
                userl.UserName = user.UserName;
            }
            #endregion
            loginInfo.UserInfo = userl;
            if (user != null)
            {
                loginInfo.Message = "登录成功！";
                loginInfo.Result = true;
                ////记录登录日志。
                UserLogManager.Log(new User_Log()
                {
                    ObjectId = user.UserGuid.ToString(),
                    Content = "用户登录",
                    AppId = AppID.ToString(),
                    FunctionId = "8020"
                });
            }
            else
            {
                loginInfo.Message = "用户名或密码错误！";
                loginInfo.Result = false;
            }
            return JsonConvert.SerializeObject(loginInfo);
        }

        /// <summary>
        /// 用户登录。（查询用户权限）
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="dogId"></param>
        /// <returns></returns>
        public override string DoLoginWithAuthority(
            string userName,
            string password,
            string dogId,
            string groupType,
            string appId)
        {
            ////获取系统登录配置信息。
            DTO.SysApplication config = GetApplicationConfig(appId);

            ////获取用户信息。
            UserInfo userInfo = GetUserInfo(
                userName,
                password,
                dogId,
                config.SiteConfig.LoginConfig.AllowLoginWithoutKey);
            try
            {
                if (userInfo.Result)
                {
                    ////烟台无key不允许登陆 2014-1-26 毛凯
                    if (!CheckUserInfo(userInfo, appId, config.SiteConfig.LoginConfig.AllowNoKeyUser).Result)
                    {
                        return JsonConvert.SerializeObject(userInfo);
                    }
                    userInfo = InitUserAuthority(userInfo, appId);
                    if (string.IsNullOrEmpty(userInfo.RoleType))
                    {
                        userInfo.Result = false;
                        userInfo.Message = "用户未关联角色类型！";
                    }
                    else if (userInfo.RoleType.Trim() == groupType.Trim())
                    {
                        ////记录登录日志。
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "用户[" + userInfo.UserName + "]登录",
                            ObjectId = userInfo.UserGuid,
                            IsrtUser = userInfo.UserGuid,
                            IsrtUserName = userInfo.UserName
                        });
                    }
                    else
                    {
                        userInfo.Result = false;
                        userInfo.Message = "登录用户类型错误！";
                    }
                }
            }
            catch (Exception ex)
            {
                userInfo.Result = false;
                userInfo.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(userInfo);
        }

        public override string DoLoginWithAuthority(string userGuid, string appId)
        {
            ////获取用户信息。
            UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(GetUserInfo(userGuid, string.Empty));
            try
            {
                if (userInfo.Result)
                {
                    userInfo = InitUserAuthority(userInfo, appId);
                }
            }
            catch (Exception ex)
            {
                userInfo.Result = false;
                userInfo.Message = ex.Message;
            }
            return JsonConvert.SerializeObject(userInfo);
        }

        public override string GetUserInfo(string userguid, string areaCode)
        {
            UserInfo userInfo = new UserInfo();
            Guid gUserGuid = Guid.Empty;
            if (Guid.TryParse(userguid, out gUserGuid))
            {
                T_Sys_Users_Zbdl user = null;
                var dbUser = dbContext.T_Sys_Users;
                user = dbUser.FirstOrDefault(
                    u => u.UserGuid == gUserGuid);
                if (user != null)
                {
                    userInfo = GetUserModel(user, false);
                    userInfo.Result = true;
                    userInfo.Message = "登录成功";
                }
            }
            else
            {
                userInfo.Result = false;
                userInfo.Message = "用户编号格式有误：不能转换为GUID类型！";
            }
            return JsonConvert.SerializeObject(userInfo);
        }
        /// <summary>
        /// 根据key号获取用户信息，含用户是否主管
        /// </summary>
        /// <param name="dogid"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetUserInfobyDogID(int dogid, string areaCode)
        {
            UserInfo userInfo = new UserInfo();

            T_Sys_Users_Zbdl user = null;
            var dbUser = dbContext.T_Sys_Users;
            user = dbUser.FirstOrDefault(
                u => u.DogID == dogid);
            if (user != null)
            {
                userInfo = GetUserModel(user, false);

                #region 是否主管判断
                bool isManager = false;
                var role = (from re in dbContext.SysUserRoles
                            join r in dbContext.SysRoles on re.RoleGuid equals r.RoleGuid
                            where re.UserGuid == user.UserGuid
                            select r).FirstOrDefault();

                if (role != null)
                {
                    if (role.GroupId == 2)
                        isManager = true;
                }
                #endregion
                userInfo.IsManager = isManager;
                userInfo.Result = true;
                userInfo.Message = "查找成功";
            }
            return JsonConvert.SerializeObject(userInfo);
        }
        /// 通过企业组织机构代码获取企业信息
        /// </summary>
        /// <param name="OrginazationCode"></param>
        /// <returns></returns>
        public override List<DTO.Tb_Corp_CompanyInfo> GetCompanyInfo(string OrginazationCode, string areaCode)
        {
            var comps = dbContext.Corp_CompanyInfos;
            var model = comps.Where(r => r.OrginazationCode == OrginazationCode).ToList();
            List<DTO.Tb_Corp_CompanyInfo> list = null;
            if (model != null)
            {
                list = new List<DTO.Tb_Corp_CompanyInfo>();
                DTO.Tb_Corp_CompanyInfo newCo = null;
                foreach (Tb_Corp_CompanyInfo_Zbdl co in model)
                {
                    newCo = new DTO.Tb_Corp_CompanyInfo();
                    EntityHelper.ConvertEntity2OtherEntity(co, newCo);
                    list.Add(newCo);
                }
            }
            return list;
        }

        protected override UserInfo InitUserAuthority(UserInfo userInfo, string appId)
        {
            AuthorityBLL authorityBll = new AuthorityBLL();
            ////1.获取用户角色。
            List<DTO.T_Sys_Roles> roles = authorityBll.GetRolesByUserGuid(userInfo.UserGuid);
            if (roles != null && roles.Count > 0)
            {
                userInfo.RoleType = roles[0].GroupCode;
                userInfo.RoleTypeTitle = roles[0].GroupTitle;
                ////2.获取用户权限字符串。
                List<string> codes = authorityBll.GetUserFuncCodes(userInfo.UserGuid, false, appId);
                string funcPerm = string.Empty;
                foreach (string code in codes)
                {
                    funcPerm += code.ToLower() + ",";
                }
                funcPerm = funcPerm.TrimEnd(',');
                userInfo.FuncPerm = funcPerm;
                return userInfo;
            }
            else
            {
                throw new Exception("用户没有设置相应的角色！");
            }
        }

        public override DTO.SysApplication GetApplicationConfig(string appId)
        {
            int iAppid = 0;
            int.TryParse(appId, out iAppid);
            var query = from app in dbContext.SysApp
                        where app.AppId == iAppid && app.IsDel == false
                        select app;
            var application = query.FirstOrDefault();
            if (application != null)
            {
                return new DTO.SysApplication()
                {
                    Id = application.Id,
                    AppId = application.AppId,
                    KeyGuid = application.KeyGuid,
                    Description = application.Description,
                    IsDel = application.IsDel,
                    SiteConfig = string.IsNullOrEmpty(application.SiteConfig) ? null : JsonConvert.DeserializeObject<DTO.SysSiteCfg>(application.SiteConfig),
                    StyleConfig = string.IsNullOrEmpty(application.StyleConfig) ? null : JsonConvert.DeserializeObject<DTO.SysStyleCfg>(application.StyleConfig)
                };
            }
            else
            {
                return null;
            }
        }

        protected override UserInfo GetUserInfo(
            string userName,
            string password,
            string dogId,
            bool allowLoginWithoutKey)
        {
            UserInfo userInfo = new UserInfo();
            T_Sys_Users_Zbdl user = null;
            var dbUser = dbContext.T_Sys_Users;
            ////有key不需要用户名
            if (string.IsNullOrEmpty(userName))
            {
                #region
                ////1.首先判断企业Key。
                user = dbUser.Where(u => u.Pwd == password && SqlFunctions.StringConvert((double)u.DogID).Trim() == dogId).ToList().LastOrDefault();
                if (user != null)
                {
                    userInfo = GetUserModel(user, false);
                    userInfo.Result = true;
                    userInfo.Message = "登录成功";
                }
                else        ////2.然后判断个人Key。
                {
                    var dbEmp = dbContext.Emp_Manager;
                    var query = from emp in dbEmp
                                join users in dbUser on emp.CorpGuid equals users.UserGuid
                                where SqlFunctions.StringConvert((double)emp.empdogid).Trim() == dogId &&
                                users.Pwd == password
                                select users;
                    user = query.FirstOrDefault();
                    if (user != null)
                    {
                        userInfo = GetUserModel(user, true);
                        userInfo.Result = true;
                        userInfo.Message = "登录成功";
                    }
                    else        ////3.置换Key。
                    {
                        var dbCert = dbContext.caCert;
                        var dbCompany = dbContext.Corp_CompanyInfos;
                        var dbManager = dbContext.Emp_Manager;
                        var query1 = from users in dbUser
                                     join company in dbCompany
                                     on users.UserGuid equals company.CorpUserGuid
                                     join cert in dbCert
                                     on new { EntityGuid = company.CorpGuid, EntityType = (Boolean)false }
                                     equals new { cert.EntityGuid, cert.EntityType }
                                     where cert.KeySerialNo == dogId && users.Pwd == password
                                     select users;
                        var query2 = from users in dbUser
                                     join emp in dbManager
                                     on users.UserGuid equals emp.CorpGuid
                                     join cert in dbCert
                                     on new { EntityGuid = emp.CorpGuid, EntityType = true }
                                     equals new { cert.EntityGuid, cert.EntityType }
                                     where cert.KeySerialNo == dogId && users.Pwd == password
                                     select users;
                        user = query1.Union(query2).FirstOrDefault();
                        if (user != null)
                        {
                            userInfo = GetUserModel(user, true);
                            userInfo.Result = true;
                            userInfo.Message = "登录成功";
                        }
                        else
                        {
                            userInfo.Result = false;
                            userInfo.Message = "登录失败！用户名、密码或数字证书号有误！";
                        }
                    }
                }
                #endregion
            }
            ////有key用户登录。
            else if (!string.IsNullOrEmpty(dogId))
            {
                #region
                ////1.首先判断企业Key。
                user = dbUser.FirstOrDefault(
                    u =>
                        u.UserName == userName &&
                        u.Pwd == password &&
                        SqlFunctions.StringConvert((double)u.DogID).Trim() == dogId);
                if (user != null)
                {
                    userInfo = GetUserModel(user, false);
                    userInfo.Result = true;
                    userInfo.Message = "登录成功";
                }
                else        ////2.然后判断个人Key。
                {
                    var dbEmp = dbContext.Emp_Manager;
                    var query = from emp in dbEmp
                                join users in dbUser on emp.CorpGuid equals users.UserGuid
                                where SqlFunctions.StringConvert((double)emp.empdogid).Trim() == dogId &&
                                users.UserName == userName &&
                                users.Pwd == password
                                select users;
                    user = query.FirstOrDefault();
                    if (user != null)
                    {
                        userInfo = GetUserModel(user, true);
                        userInfo.Result = true;
                        userInfo.Message = "登录成功";
                    }
                    else        ////3.置换Key。
                    {
                        var dbCert = dbContext.caCert;
                        var dbCompany = dbContext.Corp_CompanyInfos;
                        var dbManager = dbContext.Emp_Manager;
                        var query1 = from users in dbUser
                                     join company in dbCompany
                                     on users.UserGuid equals company.CorpUserGuid
                                     join cert in dbCert
                                     on new { EntityGuid = company.CorpGuid, EntityType = (Boolean)false }
                                     equals new { cert.EntityGuid, cert.EntityType }
                                     where cert.KeySerialNo == dogId && users.UserName == userName && users.Pwd == password
                                     select users;
                        var query2 = from users in dbUser
                                     join emp in dbManager
                                     on users.UserGuid equals emp.CorpGuid
                                     join cert in dbCert
                                     on new { EntityGuid = emp.CorpGuid, EntityType = true }
                                     equals new { cert.EntityGuid, cert.EntityType }
                                     where cert.KeySerialNo == dogId && users.UserName == userName && users.Pwd == password
                                     select users;
                        user = query1.Union(query2).FirstOrDefault();
                        if (user != null)
                        {
                            userInfo = GetUserModel(user, true);
                            userInfo.Result = true;
                            userInfo.Message = "登录成功";
                        }
                        else
                        {
                            userInfo.Result = false;
                            userInfo.Message = "登录失败！用户名、密码或数字证书号有误！";
                        }
                    }
                }
                #endregion
            }
            else
            {
                #region
                var query = from users in dbUser
                            where users.UserName == userName && users.Pwd == password
                            select users;
                user = query.FirstOrDefault();
                if (user != null)
                {
                    if (user.DogID > 0 && !allowLoginWithoutKey)
                    {
                        userInfo.Result = false;
                        userInfo.Message = "登录失败！请插入数字证书设备！";
                    }
                    else
                    {
                        userInfo = GetUserModel(user, true);
                        userInfo.Result = true;
                        userInfo.Message = "登录成功";
                    }
                }
                else
                {
                    userInfo.Result = false;
                    userInfo.Message = "登录失败！用户名或密码有误！";
                }
                #endregion
            }

            return userInfo;
        }

        private UserInfo GetUserModel(T_Sys_Users_Zbdl user, bool isPrivateKey)
        {
            return new UserInfo()
            {
                AreaCode = user.AreaCodeScope ?? user.AreaCode,
                AreaCode2 = user.AreaCode,
                DogId = user.DogID.ToString(),
                FuncPerm = string.Empty,
                IsPrivateKey = isPrivateKey,
                Name = user.Name,
                UserGuid = user.UserGuid.ToString(),
                UserID = user.ID,
                UserName = user.UserName,
                RoleId = user.RoleID.ToString(),
                Password = user.Pwd,
                UserTel = user.userTel
            };
        }

        private IList<int> GetRoleCollection(string userType)
        {
            IList<int> roleIdCollections = new List<int>();
            switch (userType.Trim().ToLower())
            {
                case "manager":
                    roleIdCollections.Add(102);
                    roleIdCollections.Add(101);//zbdlry威海添加
                    //roleIdCollections.Add(6956);
                    //roleIdCollections.Add(6547);
                    //roleIdCollections.Add(7064);
                    //roleIdCollections.Add(7032);

                    ////安监站
                    if (ConfigurationManager.AppSettings["anjianrole"] != null)
                    {
                        string[] anjianrole = ConfigurationManager.AppSettings["anjianrole"].ToString().Split(',');
                        foreach (string role in anjianrole)
                        {
                            if (!string.IsNullOrEmpty(role))
                            {
                                roleIdCollections.Add(Convert.ToInt32(role));
                            }
                        }
                    }
                    ////质安
                    if (ConfigurationManager.AppSettings["zhianrole"] != null)
                    {
                        string[] zhianrole = ConfigurationManager.AppSettings["zhianrole"].ToString().Split(',');
                        foreach (string role in zhianrole)
                        {
                            if (!string.IsNullOrEmpty(role))
                            {
                                roleIdCollections.Add(Convert.ToInt32(role));
                            }
                        }
                    }

                    ////建管
                    if (ConfigurationManager.AppSettings["jianguanrole"] != null)
                    {
                        string[] jianguanrole = ConfigurationManager.AppSettings["jianguanrole"].ToString().Split(',');
                        foreach (string role in jianguanrole)
                        {
                            if (!string.IsNullOrEmpty(role))
                            {
                                roleIdCollections.Add(Convert.ToInt32(role));
                            }
                        }
                    }
                    break;
                case "corp":
                    roleIdCollections.Add(15);
                    roleIdCollections.Add(17);
                    roleIdCollections.Add(105);
                    roleIdCollections.Add(42);
                    roleIdCollections.Add(46);
                    roleIdCollections.Add(30);
                    roleIdCollections.Add(31);
                    roleIdCollections.Add(45);
                    roleIdCollections.Add(55);
                    break;
            }
            return roleIdCollections;
        }

        #region 变更功能。

        public override string GetChangeItems(string changeType, string appId, string areaCode)
        {
            IList<Tb_ChangeItemEx> items = null;
            string[] types = changeType.Split(',');
            List<int> itemTypeArray = new List<int>();
            foreach (string str in types)
            {
                if (!string.IsNullOrEmpty(str))
                    itemTypeArray.Add(GetChangeType(str));
            }

            if (itemTypeArray.Count > 0)
            {
                items = dbContext.ChangeItems.Where(c => itemTypeArray.Contains(c.ItemType ?? 0) && c.IsDel != true && c.ClassID == 8020 && c.AppId == appId.Trim()).OrderBy(c => c.SortCode).ToList();
                if (items == null || items.Count == 0)
                {
                    items = dbContext.ChangeItems.Where(c => itemTypeArray.Contains(c.ItemType ?? 0) && c.IsDel != true && c.ClassID == 8020 && c.AppId == "0").OrderBy(c => c.SortCode).ToList();
                }
            }
            return JsonConvert.SerializeObject(items);
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="empGuid"></param>
        /// <param name="classID"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        private bool SetUserLog(string message, string ObjectId, string IsrtUser, string IsrtUserName, string areaCode, string FunctionType)
        {
            SetUserLog(message, ObjectId, IsrtUser, IsrtUserName, areaCode, FunctionType, "8020");
            return true;
        }
        /// <summary>
        /// 添加变更申请（添加变更和添加并上报使用此方法，添加并上报时需给changeSetInfo.id赋值）
        /// </summary>
        /// <param name="changeInfo"></param>
        /// <returns></returns>
        public override string AddChange(
            string changeSetInfo,
            string changeInfo,
            string changeType,
            string userGuid,
            string userRole,
            string userName, string areaCode)
        {
            bool isexist = false;
            int changesetid = 0;
            int itemType = GetChangeType(changeType);//变更类型
            string sItemType = itemType.ToString();
            OperationResult result = new OperationResult();
            Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.Where(f => f.ObjectId == userGuid && areaCode.StartsWith(f.AreaCode) && f.IsDel == false).FirstOrDefault();
            if ((flow == null || !flow.FlowCode.StartsWith("1")) && itemType < 4)
            {
                result.Message = "企业尚未通过审核！";
                result.Result = false;
                result.ReturnValue = null;
            }
            else if (!string.IsNullOrEmpty(changeInfo) && !string.IsNullOrEmpty(changeSetInfo))
            {
                ////首先验证针对此变更信息是否未结。
                Tb_ChangeSetRecordEx changeSet = JsonConvert.DeserializeObject<Tb_ChangeSetRecordEx>(changeSetInfo);
                var lastChangeSet = from cs in dbContext.ChangeSetInfo
                                    where cs.ObjectType == sItemType && (cs.IsDel == false || cs.IsDel == null) && cs.ObjectId == changeSet.ObjectId
                                    orderby cs.IsrtDate descending
                                    select cs.FlowCode;
                if (lastChangeSet.Count() == 0 || lastChangeSet.First<string>().StartsWith("1"))
                {
                    DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
                    con.Open();
                    using (DbTransaction tran = con.BeginTransaction())
                    {
                        try
                        {
                            if (sItemType == "7" || sItemType == "1")
                            {
                                Tb_ChangeSetRecordEx oldchangeinfo = dbContext.ChangeSetRecords.Where(c => (c.ObjectType == "1" || c.ObjectType == "7") &&
                                    c.IsDel != true && c.ObjectId == changeSet.ObjectId && c.IsrtDate == changeSet.IsrtDate).ToList().FirstOrDefault();
                                if (oldchangeinfo != null)
                                {
                                    isexist = true;
                                    changesetid = oldchangeinfo.Id;
                                    Tb_ChangeSetRecordEx newchange = new Tb_ChangeSetRecordEx();
                                    newchange.ObjectType = oldchangeinfo.ObjectType + "," + itemType.ToString();
                                    EntityHelper.ConvertEntity2Entity<Tb_ChangeSetRecordEx>(newchange, oldchangeinfo);
                                    dbContext.SaveChanges();
                                }
                                else
                                {
                                    //1.插入变更集合表
                                    changeSet.ObjectType = itemType.ToString();
                                    changeSet.IsDel = false;
                                    dbContext.ChangeSetRecords.Add(changeSet);
                                    dbContext.SaveChanges();
                                }
                            }
                            else
                            {
                                //1.插入变更集合表
                                changeSet.ObjectType = itemType.ToString();
                                changeSet.IsDel = false;
                                changeSet.SetAreaCode = areaCode;
                                dbContext.ChangeSetRecords.Add(changeSet);
                                dbContext.SaveChanges();
                            }

                            //2.插入变更详细信息表
                            List<Tb_ChangeRecordEx> recList = JsonConvert.DeserializeObject<List<Tb_ChangeRecordEx>>(changeInfo);
                            foreach (Tb_ChangeRecordEx item in recList)
                            {
                                item.ChangeSetId = changeSet.Id;
                                if (isexist)
                                {
                                    item.ChangeSetId = changesetid;
                                }
                                item.OptDate = changeSet.IsrtDate;
                                dbContext.ChangeRecords.Add(item);
                                dbContext.SaveChanges();
                            }

                            //string classid=this.GetClassIDbyGuid(changeSet.ObjectId, "change");
                            int codeType = 8020;
                            //int.TryParse(classid, out codeType);

                            int appid = 97;
                            int.TryParse(ConfigurationManager.AppSettings["AppID"], out appid);
                            ////3.记录审核状态。
                            Tb_FlowCode_Zbdl flowCode = new Tb_FlowCode_Zbdl()
                            {
                                AreaCode = areaCode.Substring(0, 2),
                                FlowCode = "0",
                                CodeType = codeType,
                                ObjectId = changeSet.Id.ToString(),
                                UpdateTime = DateTime.Now,
                                RoleId = userRole,
                                IsDel = false,
                                AppID = appid

                            };
                            dbContext.FlowCodes.Add(flowCode);
                            dbContext.SaveChanges();

                            ////4.插入日志表。
                            SetUserLog("添加信息变更", changeSet.Id.ToString(), userGuid, userName, areaCode.Substring(0, 2), "1");
                            //UserLogManager.Log(new User_Log()
                            //{
                            //    Content = "添加信息变更",
                            //    ObjectId = changeSet.Id.ToString(),
                            //    IsrtUser = userGuid,
                            //    IsrtUserName = userName,
                            //    IsrtUserArea = areaCode,
                            //    FunctionId = "8020",
                            //    FunctionType = "1",////1企业变更添加，3上报
                            //    AppId = AppID
                            //});

                            tran.Commit();

                            ////5.填充返回结果。
                            result.Message = "添加信息变更成功";
                            result.Result = true;
                            result.ReturnValue = changeSet;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            //插入日志表
                            SysLogManager.Log(new Sys_Log()
                            {
                                ErrorMessage = ex.Message,
                                LogDate = DateTime.Now
                            });
                            result.Message = "变更添加失败：" + ex.Message;
                            result.Result = false;
                            result.ReturnValue = null;
                        }
                        finally
                        {
                            con.Close();
                        }
                    }
                }
                else
                {
                    result.Message = "存在一条针对此数据的变更记录尚未审核通过，请先处理之前的变更申请！";
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            else
            {
                result.Message = "变更信息不完善！";
                result.Result = false;
                result.ReturnValue = null;
            }

            return JsonConvert.SerializeObject(result);
        }

        /// <summary>
        /// 提交变更申请集合（上报和修改后上报使用此方法）
        /// </summary>
        /// <param name="changeIds"></param>
        /// <returns></returns>
        public override string SubmitChange(
            string changeIds,
            string changeType,
            string userGuid,
            string userRole,
            string userName, string areaCode)
        {
            OperationResult result = new OperationResult();
            int itemType = GetChangeType(changeType);
            IList<string> changeids = JsonConvert.DeserializeObject<IList<string>>(changeIds);
            if (changeids.Count == 0)
            {
                result.Message = "请至少选择一条变更项!";
                result.Result = false;
            }
            else
            {
                DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
                con.Open();
                using (DbTransaction tran = con.BeginTransaction())
                {
                    try
                    {

                        foreach (string changeId in changeids)
                        {
                            int id = 0;
                            int.TryParse(changeId, out id);
                            string sItemType = itemType.ToString();
                            V_ChangeInfoEx changesetInfo = dbContext.ChangeSetInfo.SingleOrDefault(cs => cs.ChangeSetId == id && cs.ObjectType == sItemType && (cs.IsDel == false || cs.IsDel == null));
                            if (changesetInfo != null)
                            {
                                string contentMes = string.Empty;
                                if (changesetInfo.FlowCode.StartsWith("1"))
                                {
                                    result.Message = "变更已审核通过，不能上报！";
                                    contentMes = result.Message;
                                    result.Result = false;
                                }
                                else if (changesetInfo.FlowCode.Contains("019") && !changesetInfo.FlowCode.Contains(",021") &&
                                    !changesetInfo.FlowCode.Contains(",031"))
                                {
                                    result.Message = "变更已上报！";
                                    contentMes = result.Message;
                                    result.Result = false;
                                }
                                else
                                {
                                    var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                    userRole, string.Empty,
                                    areaCode.Substring(0, 2),
                                    "8020", changesetInfo.FlowCode, Fly.Common.WorkFlow.OptType.Post);
                                    ////1.更新状态。
                                    //if (changesetInfo.FlowCode.IndexOf("021") > 0)
                                    //{
                                    //    changesetInfo.FlowCode = "0,019,022,";
                                    //    contentMes = "再次上报变更信息";
                                    //}
                                    //else
                                    //{
                                    //    changesetInfo.FlowCode = "0,019";
                                    //    contentMes = "上报信息变更";
                                    //}

                                    if (changesetInfo.FlowCode.IndexOf("021") > 0 || changesetInfo.FlowCode.IndexOf("031") > 0)
                                    {
                                        contentMes = "再次上报变更信息";
                                    }
                                    else
                                    {
                                        contentMes = "上报变更信息";
                                    }
                                    changesetInfo.FlowCode = nextNode.NextFlowCode;
                                    dbContext.SaveChanges();
                                    ////3.填充返回结果。
                                    result.Message = "变更申请上报成功";
                                    result.Result = true;
                                    ////2.插入日志表。
                                    SetUserLog(contentMes, changeId, userGuid, userName, areaCode.Substring(0, 2), "3");

                                }
                            }
                            else
                            {
                                result.Message = "无此变更申请";
                                result.Result = false;
                            }
                        }
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        //插入日志表
                        SysLogManager.Log(new Sys_Log()
                        {
                            ErrorMessage = ex.Message,
                            LogDate = DateTime.Now
                        });
                        result.Message = "变更上报失败：" + ex.Message;
                        result.Result = false;
                        result.ReturnValue = null;
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
            return JsonConvert.SerializeObject(result);
        }

        public override string EditChange(
            string changeSetInfo,
            string changeInfo,
            string changeType,
            string userGuid,
            string userRole,
            string userName, string areaCode)
        {
            OperationResult result = new OperationResult();
            int itemType = GetChangeType(changeType);
            string sItemType = itemType.ToString();
            if (!string.IsNullOrEmpty(changeInfo) && !string.IsNullOrEmpty(changeSetInfo))
            {
                Tb_ChangeSetRecordEx changeSet = JsonConvert.DeserializeObject<Tb_ChangeSetRecordEx>(changeSetInfo);
                var lastChangeSet = from cs in dbContext.ChangeSetInfo
                                    where cs.ObjectType == sItemType && (cs.IsDel == false || cs.IsDel == null) && cs.ChangeSetId == changeSet.Id
                                    orderby cs.IsrtDate descending
                                    select cs.FlowCode;
                Tb_ChangeSetRecordEx changeSet1 = dbContext.ChangeSetRecords.SingleOrDefault(c => c.Id == changeSet.Id);
                if (changeSet1 == null)
                {
                    result.Message = "没有此项变更信息！";
                    result.Result = false;
                    result.ReturnValue = null;
                }
                else if (lastChangeSet.Count() == 0 || lastChangeSet.First() == "0" || lastChangeSet.First().Contains("021")
                    || lastChangeSet.First().Contains("031"))
                {
                    DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
                    con.Open();
                    using (DbTransaction tran = con.BeginTransaction())
                    {
                        try
                        {
                            DateTime optDate = DateTime.Now;
                            ////1.删除变更子项信息。
                            ChangeDALWh ChangeDALWh = new ChangeDALWh(dbContext);
                            ChangeDALWh.DeleteChanges(changeSet.Id);
                            dbContext.SaveChanges();

                            ////2.更新变更主表。
                            changeSet1.Description = changeSet.Description;
                            //changeSet1.IsrtDate = optDate;
                            changeSet1.ObjectType = sItemType;
                            changeSet1.ObjectName = changeSet.ObjectName;
                            dbContext.SaveChanges();

                            ////3.添加子表。
                            List<Tb_ChangeRecordEx> recList = JsonConvert.DeserializeObject<List<Tb_ChangeRecordEx>>(changeInfo);
                            foreach (Tb_ChangeRecordEx item in recList)
                            {
                                item.ChangeSetId = changeSet.Id;
                                item.OptDate = optDate;
                                dbContext.ChangeRecords.Add(item);
                                dbContext.SaveChanges();
                            }

                            //var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                            //       userRole, string.Empty,
                            //       areaCode.Substring(0, 2),
                            //       "8020", lastChangeSet.First(), Fly.Common.WorkFlow.OptType.Post);
                            //////4.修改审核状态为 再次上报。
                            //string changeSetID = changeSet.Id.ToString();
                            //Tb_FlowCode_Zbdl flowCode = dbContext.FlowCodes.Where(c => c.ObjectId == changeSetID && c.CodeType == 8020 &&
                            //    (c.IsDel == false || c.IsDel == null)).FirstOrDefault();
                            //flowCode.FlowCode = nextNode.NextFlowCode;
                            //dbContext.SaveChanges();

                            ////5.插入日志表。
                            SetUserLog("修改信息变更", changeSet.Id.ToString(), userGuid, userName, areaCode.Substring(0, 2), "2");


                            tran.Commit();

                            ////6.填充返回结果。
                            result.Message = "变更申请修改成功";
                            result.Result = true;
                            result.ReturnValue = changeSet;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            //插入日志表
                            SysLogManager.Log(new Sys_Log()
                            {
                                ErrorMessage = ex.Message,
                                LogDate = DateTime.Now
                            });
                            result.Message = "变更修改失败：" + ex.Message;
                            result.Result = false;
                            result.ReturnValue = null;
                        }
                        finally
                        {
                            con.Close();
                        }
                    }
                }
                else
                {
                    result.Message = "此项信息正在审核中，不允许修改！";
                    result.Result = false;
                    result.ReturnValue = null;
                }
            }
            else
            {
                result.Message = "变更信息不完善！";
                result.Result = false;
                result.ReturnValue = null;
            }

            return JsonConvert.SerializeObject(result);
        }

        public override string DeleteChange(
            string changeId,
            string changeType,
            string userGuid,
            string userRole,
            string userName, string areaCode)
        {
            OperationResult result = new OperationResult();

            int changeid = 0;
            int.TryParse(changeId, out changeid);
            int itemType = GetChangeType(changeType);
            string sItemType = itemType.ToString();
            var lastChangeSet = from cs in dbContext.ChangeSetInfo
                                where cs.ObjectType == sItemType && (cs.IsDel == false || cs.IsDel == null) && cs.ChangeSetId == changeid
                                orderby cs.IsrtDate descending
                                select cs.FlowCode;
            Tb_ChangeSetRecordEx changeSet = dbContext.ChangeSetRecords.SingleOrDefault(c => c.Id == changeid && (c.IsDel == false || c.IsDel == null) && c.ObjectType == sItemType);
            if (changeSet == null)
            {
                result.Message = "没有此项变更！";
                result.Result = false;
                result.ReturnValue = null;
            }
            else if (lastChangeSet.Count() == 0 || lastChangeSet.First() == "0" || lastChangeSet.First().Contains("021")
                    || lastChangeSet.First().Contains("031"))
            {
                changeSet.IsDel = true;
                dbContext.SaveChanges();
                result.Message = "删除变更成功！";
                result.Result = true;
                result.ReturnValue = null;
            }
            else if (lastChangeSet.First().StartsWith("1"))
            {
                result.Message = "此项信息已通过审核，不允许删除！";
                result.Result = false;
                result.ReturnValue = null;
            }
            else
            {
                result.Message = "此项信息正在审核中，不允许删除！";
                result.Result = false;
                result.ReturnValue = null;
            }

            return JsonConvert.SerializeObject(result);
        }

        public override string GetBeforeChangeValue(string changeItem, string areaCode, params string[] parameters)
        {
            if (StringHelper.SqlFilter(parameters))
            {
                return null;
            }
            string appId = "0";
            if (ConfigurationManager.AppSettings["AppId"] != null)
            {
                appId = ConfigurationManager.AppSettings["AppId"];
            }
            Tb_ChangeItemEx cItem = dbContext.ChangeItems.SingleOrDefault(c => c.ChangeItem == changeItem && c.AppId == appId && (c.IsDel == false || c.IsDel == null) && c.ClassID == 8020);
            if (cItem == null)
            {
                cItem = dbContext.ChangeItems.SingleOrDefault(c => c.ChangeItem == changeItem && c.AppId == "0" && (c.IsDel == false || c.IsDel == null) && c.ClassID == 8020);
            }

            if (cItem != null)
            {
                string strSql = string.Format(cItem.BeforeSQL, parameters);
                List<KeyValue> result = dbContext.Database.SqlQuery<KeyValue>(strSql).ToList();
                if (result.Count > 0)
                {
                    Dictionary<string, string> dicValue = new Dictionary<string, string>();
                    dicValue.Add(result[0].Key ?? string.Empty, result[0].Value ?? string.Empty);
                    return JsonConvert.SerializeObject(dicValue);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        public override string GetBindChangeValue(string changeItem, string areaCode, params string[] parameters)
        {
            if (StringHelper.SqlFilter(parameters))
            {
                return null;
            }
            string appId = "0";
            if (ConfigurationManager.AppSettings["AppId"] != null)
            {
                appId = ConfigurationManager.AppSettings["AppId"];
            }
            Tb_ChangeItemEx cItem = dbContext.ChangeItems.SingleOrDefault(c => c.ChangeItem == changeItem && c.AppId == appId && (c.IsDel == false || c.IsDel == null) && c.ClassID == 8020);
            if (cItem == null)
            {
                cItem = dbContext.ChangeItems.SingleOrDefault(c => c.ChangeItem == changeItem && c.AppId == "0" && (c.IsDel == false || c.IsDel == null) && c.ClassID == 8020);
            }
            if (cItem == null)
            {
                return null;
            }
            string strSql = string.Empty;
            if (parameters == null || parameters.Length == 0)
            {
                strSql = cItem.BindSQL;
            }
            else if (cItem.BindSQL != null)
            {
                strSql = string.Format(cItem.BindSQL, parameters);
            }
            List<KeyValue> result = dbContext.Database.SqlQuery<KeyValue>(strSql).ToList();
            if (result.Count > 0)
            {
                Dictionary<string, string> dicValue = new Dictionary<string, string>();
                foreach (KeyValue kv in result)
                {
                    if (dicValue.Keys.Contains(kv.Key))
                    {
                        continue;
                    }
                    dicValue.Add(kv.Key, kv.Value);
                }
                return JsonConvert.SerializeObject(dicValue);
            }
            else
            {
                return null;
            }
        }

        public override string GetChanges(string changeType, string corpUserGuid, string flowCode, string condition, int pageIndex, int pageSize, out int count, string areaCode)
        {
            count = 0;
            if (!string.IsNullOrEmpty(condition))
            {
                if (StringHelper.SqlFilter(condition))
                {
                    return "查询条件包含非法字符!";
                }
            }

            ChangeDALWh ChangeDALWh = new ChangeDALWh(this.dbContext);
            IList<V_ChangeInfoEx> changeInfos = ChangeDALWh.GetChanges(GetChangeType(changeType).ToString(), corpUserGuid, flowCode, condition, pageIndex, pageSize, out  count);
            //foreach (V_ChangeInfo changeInfo in changeInfos)
            //{
            //   changeInfo.StrFlowCode = FlowHelper.GetQdFlowName(changeInfo.FlowCode);
            //}
            return JsonConvert.SerializeObject(changeInfos);

        }

        public override string GetChangeDetails(string changeType, int changeSetId, string areaCode)
        {
            int itemType = GetChangeType(changeType);
            string sItemType = itemType.ToString();
            Tb_ChangeSetRecordEx changeSetInfo;
            if (itemType == 1)
            {
                changeSetInfo = dbContext.ChangeSetRecords.SingleOrDefault(cs => cs.Id == changeSetId && (cs.ObjectType == "1" || cs.ObjectType == "3" || cs.ObjectType == "7" || cs.ObjectType == "1,7" || cs.ObjectType == "7,1") && (cs.IsDel == false || cs.IsDel == null));
            }
            else if (itemType == 4)
            {
                changeSetInfo = dbContext.ChangeSetRecords.SingleOrDefault(cs => cs.Id == changeSetId && (cs.ObjectType == "4" || cs.ObjectType == "6") && (cs.IsDel == false || cs.IsDel == null));
            }
            else if (itemType == 8)
            {
                changeSetInfo = dbContext.ChangeSetRecords.SingleOrDefault(cs => cs.Id == changeSetId && (cs.ObjectType == "1,7" || cs.ObjectType == "7,1") && (cs.IsDel == false || cs.IsDel == null));
            }
            else
            {
                changeSetInfo = dbContext.ChangeSetRecords.SingleOrDefault(cs => cs.Id == changeSetId && cs.ObjectType == sItemType && (cs.IsDel == false || cs.IsDel == null));
            }
            if (changeSetInfo == null)
            {
                return "";
            }
            IList<Tb_ChangeRecordEx> changeInfos = dbContext.ChangeRecords.Where(c => c.ChangeSetId == changeSetId).ToList();
            ChangeDetailEx changeDetail = new ChangeDetailEx();
            changeDetail.ChangeSet = changeSetInfo;
            changeDetail.ChangeInfos = changeInfos;
            return JsonConvert.SerializeObject(changeDetail);
        }

        private int GetChangeType(string changeType)
        {
            int itemType = 0;
            switch (changeType.ToLower())
            {
                case "corp":
                    itemType = 1;
                    break;
                case "safe":
                    itemType = 3;
                    break;
                case "corpquality":
                    itemType = 2;
                    break;
                case "person":
                    itemType = 4;
                    break;
                case "personquality":
                    itemType = 5;
                    break;
                case "personqualityb":
                    itemType = 6;
                    break;
                case "corpwdrq":
                    itemType = 7;
                    break;
                case "corpall":
                    itemType = 8;
                    break;
                case "personwork":
                    itemType = 9;
                    break;
                case "personpost":
                    itemType = 10;
                    break;
                case "expert":
                    itemType = 11;
                    break;
            }
            return itemType;
        }

        public string GetClassValue(string changeItem, params string[] parameters)
        {
            if (StringHelper.SqlFilter(parameters))
            {
                return "查询条件包含非法字符!";
            }
            Tb_ChangeItemEx cItem = dbContext.ChangeItems.SingleOrDefault(c => c.ChangeItem == changeItem && (c.IsDel == false || c.IsDel == null) && c.ClassID == 8020);
            if (cItem != null)
            {
                string strSql = string.Empty;
                if (parameters == null || parameters.Length == 0)
                {
                    strSql = cItem.BindSQL;
                }
                else
                {
                    strSql = string.Format(cItem.BindSQL, parameters);
                }
                List<KeyValue> result = dbContext.Database.SqlQuery<KeyValue>(strSql).ToList();
                if (result.Count > 0)
                {
                    Dictionary<string, string> dicValue = new Dictionary<string, string>();
                    foreach (KeyValue kv in result)
                    {
                        if (dicValue.Keys.Contains(kv.Key))
                        {
                            continue;
                        }
                        dicValue.Add(kv.Key, kv.Value);
                    }
                    return JsonConvert.SerializeObject(dicValue);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }

        public override string CheckChange(string changeSetId, string userRole, string areaCode)
        {
            List<OperationResult> list = new List<OperationResult>();
            Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.Where(f => f.ObjectId == changeSetId && areaCode.StartsWith(f.AreaCode) && (f.IsDel ==
                false || f.IsDel == null) && f.CodeType == 8020).FirstOrDefault();
            OperationResult result = null;
            if (flow != null)
            {
                for (int i = 4; i <= 6; i++)
                {
                    result = new OperationResult();
                    var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                            userRole, string.Empty,
                                            areaCode.Substring(0, 2),
                                            "8020", flow.FlowCode, (Fly.Common.WorkFlow.OptType)i);
                    result.Result = nextNode.Result;
                    result.Message = i + "," + nextNode.Message;
                    result.ReturnValue = nextNode.NextFlowCode;
                    list.Add(result);
                }
            }
            else
            {
                result = new OperationResult();
                result.Result = false;
                result.Message = "无此变更申请";
                result.ReturnValue = null;
                list.Add(result);
            }
            return JsonConvert.SerializeObject(list);
        }

        public override List<DTO.tb_Emp_Manager> GetChangeEmpList(string conditions, int pageCount, int pageSize)
        {
            var query = from emps in dbContext.Emp_Manager
                        where emps.IsDel == null || emps.IsDel == false
                        select new DTO.tb_Emp_Manager
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            EmployeeType = emps.EmployeeType,
                            GraduatedSchool = emps.GraduatedSchool,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            Name = emps.Name,
                            Sex = emps.Sex,
                            Tel = emps.Tel,
                            TypeFlag = emps.TypeFlag
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<DTO.QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<DTO.tb_Emp_Manager>(condition);
            }
            if (pageSize > 0)
            {
                query = query.OrderBy(m => m.ID).Skip(pageCount * pageSize).Take(pageSize);
            }
            var list = query.ToList();

            return list;
        }
        public override int GetChangeEmpCount(string conditions)
        {
            var query = from emps in dbContext.Emp_Manager
                        where emps.IsDel == null || emps.IsDel == false
                        select new DTO.tb_Emp_Manager
                        {
                            #region 封装实体
                            EmpGuid = emps.EmpGuid,
                            AreaCode = emps.AreaCode,
                            ClassId = emps.ClassId,
                            CorpClassID = emps.CorpClassID,
                            CorpGuid = emps.CorpGuid,
                            CorpID = emps.CorpID,
                            ID = emps.ID,
                            IDCard = emps.IDCard,
                            IDType = emps.IDType,
                            Name = emps.Name,
                            Sex = emps.Sex,
                            #endregion
                        };
            if (!string.IsNullOrEmpty(conditions))
            {
                var condition = JsonConvert.DeserializeObject<IList<DTO.QueryPersonInfoCondition>>(conditions);
                query = query.BuildCondition<DTO.tb_Emp_Manager>(condition);
            }
            return query.Count();
        }

        /// <summary>
        /// 返回变更项需要上传的图片
        /// </summary>
        /// <returns></returns>
        public override string GetChangeItemUploadImg(string uploadID, string areaCode)
        {
            if (string.IsNullOrEmpty(uploadID))
            {
                return null;
            }
            int code = 0;
            List<int> codes = new List<int>();
            foreach (string a in uploadID.Split(','))
            {
                if (int.TryParse(a, out code))
                {
                    codes.Add(code);
                }
            }
            var list = dbContext.ChangeItemUploadEx.Where(c => codes.Contains(c.Code ?? 0)).Distinct().ToList();
            return JsonConvert.SerializeObject(list);
        }

        #endregion

        #region 变更审核

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="changeId">setid</param>
        /// <param name="flowCode">审核状态</param>
        /// <param name="description">审核意见</param>
        /// <param name="isFinal"></param>
        /// <param name="changeType">变更类型</param>
        /// <param name="userGuid">用户guid</param>
        /// <param name="userRole">用户角色</param>
        /// <param name="userName">用户名</param>
        /// <param name="areaCode">地区</param>
        /// <returns></returns>
        public override string AuditChange(
            string changeId,
            string flowCode,
            string description,
            bool isFinal,
            string changeType,
            string userGuid,
            string userRole,
            string userName,
            string areaCode)
        {
            string appId = "0";
            if (ConfigurationManager.AppSettings["AppId"] != null)
            {
                appId = ConfigurationManager.AppSettings["AppId"];
            }
            OperationResult result = new OperationResult();
            bool rst = true;
            try
            {
                Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.SingleOrDefault(r => r.ObjectId == changeId && r.CodeType == 8020 && (r.IsDel == false || r.IsDel == null));
                if (flowCode != null && flowCode == "1")  //审核通过  //未加事务处理
                {
                    var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                    userRole,
                                    string.Empty,
                                    areaCode.Substring(0, 2),
                                    "8020",
                                    flow.FlowCode,
                                    Fly.Common.WorkFlow.OptType.Audit);
                    if (nextNode.Result)
                    {
                        if (nextNode.IsFinal)
                        {
                            rst = UpdateTables(changeId, nextNode.NextFlowCode, description, appId);  ////审核通过更新数据
                            if (!rst)
                            {
                                result.Message = "操作失败";
                            }
                            else
                            {
                                result.Message = "审核信息变更通过";
                            }
                        }
                        if (rst)
                        {
                            this.UpdateFlowCode(changeId, nextNode.NextFlowCode, description);///修改状态
                        }
                    }
                    else
                    {
                        rst = false;
                        result.Message = "操作失败:" + nextNode.Message;
                    }
                }
                else //退回
                {
                    var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                   userRole,
                                   string.Empty,
                                   areaCode.Substring(0, 2),
                                   "8020",
                                   flow.FlowCode,
                                   Fly.Common.WorkFlow.OptType.Reject);
                    if (nextNode.Result)
                    {
                        rst = this.UpdateFlowCode(changeId, nextNode.NextFlowCode, description);////审核未通过修改状态
                        result.Message = "退回信息变更成功";
                    }
                    else
                    {
                        rst = false;
                        result.Message = "操作失败:" + nextNode.Message;
                    }
                }
                result.Result = rst;

                ////4.插入日志表。
                if (rst)
                {
                    string text = string.IsNullOrEmpty(description) ? "" : "：" + description;
                    string msg = flowCode.StartsWith("1") ? "主管通过" + text : "主管退回" + text;
                    SetUserLog(msg, changeId, userGuid, userName, areaCode, flowCode.StartsWith("1") ? ("4") : ("5"));
                    //UserLogManager.Log(new User_Log()
                    //{
                    //    Content = flowCode.StartsWith("1")?"主管通过"+text:"主管退回" +text,
                    //    ObjectId = changeId,
                    //    IsrtUser = userGuid,
                    //    IsrtUserName = userName,
                    //    IsrtUserArea = areaCode,
                    //    FunctionType = flowCode.StartsWith("1") ? ("4") : ("5"),////4.审核通过  5.主管退回
                    //    FunctionId = "8020",
                    //    AppId = AppID
                    //});
                }
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = "变更审核程序出错";
            }
            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 审核通过更新表数据
        /// </summary>
        /// <param name="changeId"></param>
        private bool UpdateTables(string changeId, string flowCode, string description, string appId)
        {
            ////1、获取变更集及关联数据
            var changeList = new ChangeDALWh(dbContext).GetChangeItemRecordInfo(int.Parse(changeId), appId);
            if (changeList != null && changeList.Count > 0)
            {

                Dictionary<string, string> tables = GetUpdateTables(changeList);
                if (tables != null && tables.Count > 0)
                {
                    string objectID = changeList[0].ObjectId;
                    if (string.IsNullOrEmpty(objectID))
                        return false;
                    DbConnection conn = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
                    conn.Open();
                    using (DbTransaction tran = conn.BeginTransaction())
                    {
                        try
                        {
                            #region 更新数据
                            var SqlCommands = new List<SqlCommandParameter>();

                            foreach (string table in tables.Keys)
                            {
                                List<SqlParameter> parameters = new List<SqlParameter>() { new SqlParameter("@ObjectId", objectID) };

                                string sql = string.Format("update {0} set ", table);
                                foreach (var change in changeList)
                                {
                                    if (change.UpdateTable.Split('|')[0] == table)
                                    {
                                        if (change.UpdateColumn.IndexOf('|') > 0 && (!string.IsNullOrEmpty(change.UpdateColumn.Split('|')[1])))  //处理类似”级别“这用name：value的更新
                                        {
                                            //对每一类对应表中的记录，拼接sql更新
                                            sql += string.Format("{0}=@{1},", change.UpdateColumn.Split('|')[0], change.UpdateColumn.Split('|')[0]);
                                            parameters.Add(new SqlParameter(string.Format("@{0}", change.UpdateColumn.Split('|')[0]), change.AfterChange));
                                            sql += string.Format("{0}=@{1},", change.UpdateColumn.Split('|')[1], change.UpdateColumn.Split('|')[1]);
                                            parameters.Add(new SqlParameter(string.Format("@{0}", change.UpdateColumn.Split('|')[1]), change.AfterValue));
                                        }
                                        else
                                        {
                                            switch (change.UpdateColumn.ToLower())
                                            {
                                                case "certificatename":
                                                    string sqlExt = string.Format("update tb_emp_Manager set TypeFlag=@{0} WHERE EmpGuid=(SELECT TOP 1 EmpGuid FROM dbo.tb_Emp_TitleDetails WHERE ID=@{1})", "TypeFlag", "ObjectId");
                                                    List<SqlParameter> cer_parameters = new List<SqlParameter>() { new SqlParameter("@ObjectId", objectID) };
                                                    cer_parameters.Add(new SqlParameter(string.Format("@{0}", "TypeFlag"), change.AfterValue));
                                                    SqlCommands.Add(new SqlCommandParameter() { Sql = sqlExt, Parameters = cer_parameters });
                                                    break;
                                                case "birthday":
                                                    #region 处理出生年月
                                                    string year;
                                                    string month;
                                                    ParseBirthdayYearMonth(change.AfterValue, out year, out month);
                                                    #endregion
                                                    sql += string.Format("{0}=@{1},", "BithdayYear", "BithdayYear");
                                                    parameters.Add(new SqlParameter(string.Format("@{0}", "BithdayYear"), year));
                                                    sql += string.Format("{0}=@{1},", "BithdayMonth", "BithdayMonth");
                                                    parameters.Add(new SqlParameter(string.Format("@{0}", "BithdayMonth"), month));
                                                    break;
                                                case "biso":
                                                    if (!string.IsNullOrEmpty(change.AfterValue))
                                                    {
                                                        string[] bisolist = change.AfterValue.Split(',');
                                                        sql += string.Format("{0}=@{1},", "bISO14000", "bISO14000");
                                                        parameters.Add(new SqlParameter(string.Format("@{0}", "bISO14000"), bisolist[0]));
                                                        sql += string.Format("{0}=@{1},", "bISO9000", "bISO9000");
                                                        parameters.Add(new SqlParameter(string.Format("@{0}", "bISO9000"), bisolist[1]));
                                                        sql += string.Format("{0}=@{1},", "bISO9001", "bISO9001");
                                                        parameters.Add(new SqlParameter(string.Format("@{0}", "bISO9001"), bisolist[2]));
                                                        sql += string.Format("{0}=@{1},", "bOHSMS18000", "bOHSMS18000");
                                                        parameters.Add(new SqlParameter(string.Format("@{0}", "bOHSMS18000"), bisolist[3]));
                                                    }
                                                    break;
                                            }
                                            //对每一类对应表中的记录，拼接sql更新
                                            if (change.UpdateColumn.ToLower() != "biso" && change.UpdateColumn.ToLower() != "typeflag")
                                            {
                                                sql += string.Format("{0}=@{1},", change.UpdateColumn, change.ChangeItem);
                                                parameters.Add(new SqlParameter(string.Format("@{0}", change.ChangeItem), (change.SelectType != null && change.SelectType.ToLower() == "t") ? change.AfterChange : change.AfterValue));
                                            }
                                        }
                                    }
                                }
                                if (sql != string.Format("update {0} set ", table))
                                {
                                    sql = sql.TrimEnd(',');
                                    sql += tables[table];
                                    ///执行sql
                                    dbContext.Database.ExecuteSqlCommand(sql, parameters.ToArray());
                                    SqlCommands.ForEach(r => dbContext.Database.ExecuteSqlCommand(r.Sql, r.Parameters.ToArray()));
                                }
                                //if (SqlCommands != null && SqlCommands.Count > 0)
                                //{
                                //    foreach (var sqlcom in SqlCommands)
                                //    {
                                //        dbContext.Database.ExecuteSqlCommand(sqlcom.Sql, sqlcom.Parameters.ToArray());
                                //    }
                                //}

                            }
                            #endregion

                            tran.Commit();
                            ///写日志
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            //插入日志表
                            SysLogManager.Log(new Sys_Log()
                            {
                                ErrorMessage = string.Format("变更集ID{0}：错误信息{1}", changeId, ex.Message),
                                LogDate = DateTime.Now
                            });
                            return false;
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                    #region 更新数据

                    foreach (string table in tables.Keys)
                    {
                        foreach (var change in changeList)
                        {
                            if (change.UpdateTable.Split('|')[0] == table)
                            {
                                //对每一类对应表中的记录，拼接sql更新
                                if (change.UpdateColumn.ToLower() == "typeflag" && change.IsDel == false)
                                {
                                    string sql2 = string.Empty;
                                    Guid empguid1 = Guid.Empty;
                                    Guid empguid2 = Guid.Empty;
                                    Guid.TryParse(change.BeforeValue, out empguid1);
                                    Guid.TryParse(change.AfterValue, out empguid2);
                                    var typeflag1 = empguid1 != Guid.Empty ? dbContext.Emp_Manager.Where(m => m.EmpGuid == empguid1).FirstOrDefault().TypeFlag : "0";
                                    var typeflag2 = empguid2 != Guid.Empty ? dbContext.Emp_Manager.Where(m => m.EmpGuid == empguid2).FirstOrDefault().TypeFlag : "0";

                                    RN.ERP.DTO.CorpChangeItem cci =
                                        RN.ERP.DTO.CorpChangeItem.None;
                                    cci = (RN.ERP.DTO.CorpChangeItem)Enum.Parse(typeof
                                        (RN.ERP.DTO.CorpChangeItem), change.ChangeItem);
                                    switch (cci)
                                    {
                                        case RN.ERP.DTO.CorpChangeItem.NID_Fr:
                                        case RN.ERP.DTO.CorpChangeItem.NID_Qy:
                                        case RN.ERP.DTO.CorpChangeItem.NID_Js:
                                        case RN.ERP.DTO.CorpChangeItem.NID_Cw:
                                        case RN.ERP.DTO.CorpChangeItem.NID_Jy:
                                            if (empguid2 != Guid.Empty)
                                            {
                                                var emp2 = dbContext.Emp_Manager.Where(m => m.EmpGuid == empguid2).FirstOrDefault();
                                                emp2.TypeFlag = AddNewTypeFlag(typeflag2, ((int)cci).ToString());
                                                if (empguid1 != Guid.Empty)
                                                {
                                                    var emp1 = dbContext.Emp_Manager.Where(m => m.EmpGuid == empguid1).FirstOrDefault();
                                                    emp1.TypeFlag = CancelTypeFlag(typeflag1, ((int)cci).ToString());
                                                }
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            return true;
        }

        private bool UpdateTableNew()
        {
            return false;
        }

        private static void ParseBirthdayYearMonth(string birValue, out string year, out string month)
        {
            year = "0";
            month = "0";

            bool flag = false;

            try
            {
                DateTime bir = DateTime.Now;
                DateTime.TryParse(birValue, out bir);
                year = bir.Year.ToString();
                month = bir.Month.ToString();
            }
            catch
            { flag = true; }
            if (flag)
            {
                try
                {
                    birValue = birValue.Replace('/', '-');
                    year = birValue.Split('-')[0];
                    month = birValue.Split('-')[1];
                }
                catch (Exception ex)
                {
                }

            }
        }

        /// <summary>
        /// 更改审核状态
        /// </summary>
        /// <param name="changeId"></param>
        /// <param name="flowCode"></param>
        /// <returns></returns>
        private bool UpdateFlowCode(string changeId, string flowCode, string description)
        {

            try
            {
                Tb_FlowCode_Zbdl flow = dbContext.FlowCodes.SingleOrDefault(r => r.ObjectId == changeId && r.CodeType == 8020 && (r.IsDel == false || r.IsDel == null));
                if (flow != null)
                {
                    ////1.更新状态。
                    flow.FlowCode = flowCode;
                    flow.Description = description;
                    dbContext.SaveChanges();
                    return true;
                }
            }
            catch (Exception ex)
            { //插入日志表
                SysLogManager.Log(new Sys_Log()
                {
                    ErrorMessage = ex.Message,
                    LogDate = DateTime.Now
                });
            }
            return false;
        }
        /// <summary>
        /// 提取影响的表名及where条件  一次变更集针对同一张表中的where是一致的，取第一次条件即可    
        /// </summary>
        /// <param name="changeList"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetUpdateTables(List<ChangeItemRecordInfoEx> changeList)
        {
            Dictionary<string, string> tableDict = new Dictionary<string, string>();///更改表字典 key:表名，value:where条件
            foreach (ChangeItemRecordInfoEx record in changeList)
            {
                string table = record.UpdateTable;

                if (table != null)
                {
                    string[] tableWhere = table.Split('|');
                    string tableName = table.Split('|')[0];
                    if (!tableDict.Keys.Contains(tableName))
                    {
                        if (tableWhere.Length > 2)  ///为安全期间，如果UpdateTable列中"|"个数少于2则不处理该更改
                        {
                            string where = string.Format(" where {0}=@ObjectId {1}", tableWhere[1], tableWhere[2]);
                            tableDict.Add(tableName, where);
                        }

                    }
                }
            }
            return tableDict;
        }

        public override string AuditLogs(string objectId, string areaCode)
        {
            string appId = "0";
            if (ConfigurationManager.AppSettings["AppId"] != null)
            {
                appId = ConfigurationManager.AppSettings["AppId"];
            }
            return JsonConvert.SerializeObject(new ChangeDALWh(dbContext).AuditLogs(objectId, appId));
        }

        public string AddNewTypeFlag(string OldType, string AddTypeFlag)
        {
            if (OldType == "" || OldType == "-1")
            {
                return AddTypeFlag;
            }
            else if (OldType.Contains(AddTypeFlag))//若已包含，就不再累计
            {
                return OldType;
            }
            else
            {
                return OldType + "," + AddTypeFlag;  //累计已有的
            }
        }

        public string CancelTypeFlag(string OldType, string CancelTypeFlag)
        {
            string newValue = "";
            if (OldType.Length <= 2)
            {
                newValue = "-1";
            }
            else //（2）身兼数职
            {
                newValue = OldType.Replace("," + CancelTypeFlag, "").Replace(CancelTypeFlag + ",", ""); //排除要取消的职务 .typeFlag 或 typeFlag，
            }
            return newValue;
        }
        #endregion

        #region UC控件调用
        /// <summary>
        /// 根据专业类别nid获取证书等级
        /// </summary>
        /// <param name="nid"></param>
        /// <returns></returns>
        public override List<DTO.tb_Emp_TitleType> GetPsnQualLevelByType(int nid, string areaCode)
        {
            List<int> titleclass = new List<int>();
            titleclass = (from a in dbContext.tb_Emp_TitleClass
                          where a.ClassID == nid && a.Token == "JiBie"
                          select a.NID).ToList();
            var level = (from b in dbContext.tb_Emp_TitleType
                         where titleclass.Contains(b.NID) && b.Token == "jibie"
                         select b).ToList();
            List<DTO.tb_Emp_TitleType> ret = new List<DTO.tb_Emp_TitleType>();
            foreach (tb_Emp_TitleType_Zbdl item in level)
            {
                DTO.tb_Emp_TitleType lv = new DTO.tb_Emp_TitleType();
                Fly.FlyCommon.EntityHelper.ConvertEntity2OtherEntity(item, lv);
                ret.Add(lv);
            }
            return ret;
        }
        /// <summary>
        /// 根据证书类型获取专业
        /// </summary>
        /// <param name="nid"></param>
        /// <returns></returns>
        public override List<DTO.a_Speciality> GetPsnspecialtyByQualLType(int nid, string areaCode)
        {
            //暂不将nid带入逻辑中返回固定的JZ
            List<DTO.a_Speciality> specialty = new List<DTO.a_Speciality>();
            try
            {
                specialty = (from a in dbContext.a_Speciality
                             where a.Type == "JZ"
                             select new DTO.a_Speciality { Code = a.Code, ID = a.ID, SpecialityTitle = a.SpecialityTitle }).ToList();
            }
            catch (Exception e)
            { }
            return specialty;

        }
        public override DTO.PsnQulaDDValue GetPersonQualityByGid(string qulaiguid, string areaCode)
        {
            DTO.PsnQulaDDValue td = new DTO.PsnQulaDDValue();

            try
            {
                Guid EducationGUID = Guid.Parse(qulaiguid);
                var details = dbContext.Emp_Qualities.Where(m => m.EducationGUID == EducationGUID).FirstOrDefault();
                var TypeFlags = details.TypeFlags.ToString();

                var dicZsType = dbContext.Dictionary.Where(m => m.Code == TypeFlags && m.RootCode == "ZGZS").FirstOrDefault();
                var dicZsLev = dbContext.Dictionary.Where(m => m.Code == details.CertificateLevel && m.RootCode == "ZGDJ").FirstOrDefault();
                var dicZsSpe = dbContext.Dictionary.Where(m => m.Code == details.CertificateSpecialty && m.RootCode == "specialty").FirstOrDefault();
                td.dicZsType = dicZsType.Code + "@" + dicZsType.SID;
                td.dicZsLev = dicZsLev.Code + "@" + dicZsLev.SID;
                td.dicZsSpe = dicZsSpe.Code + "@" + dicZsSpe.SID;
            }
            catch (Exception e)
            {

            }
            return td;
        }
        /// <summary>
        /// 跟去企业类型获取企业下资质等级列表
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public override List<DTO.KeyValue> GetCorpQualLevByUserGuid(int roleid, string areaCode)
        {
            List<DTO.KeyValue> list = new List<DTO.KeyValue>();
            try
            {
                list = (from a in dbContext.Dictionarys
                        from b in dbContext.Role_Kind_Grade
                        where a.ParentSID == b.ParentSID && b.RoleID == roleid
                        select new DTO.KeyValue { Key = a.Code, Value = a.Name }).ToList();
            }
            catch { }
            return list;
        }

        public override DTO.QulaDDValue GetCorpQualByGuid(string guid, string areaCode)
        {
            DTO.QulaDDValue qual = new DTO.QulaDDValue();
            Guid QualityGuid = Guid.Parse(guid);
            try
            {
                //获取资质信息
                var q = dbContext.Corp_CompanyQualities.Where(m => m.QualityGuid == QualityGuid).FirstOrDefault();
                var dicSm = new T_Sys_Dict_Zbdlry();
                var dicBig = new T_Sys_Dict_Zbdlry();
                var dicLev = new T_Sys_Dict_Zbdlry();
                string smValue = "";
                string bigValue = "";
                string levValue = "";
                if (q != null)
                {
                    var corp = dbContext.T_Sys_Users.Where(m => m.UserGuid == q.CorpUserGuid).FirstOrDefault();
                    string roleid = corp.RoleID.ToString();
                    string kindid = q.KindID.ToString();
                    ////资质获取修改 2013-11-1 毛凯
                    //获取资质小项
                    dicSm = dbContext.Dictionary.Where(m => m.Code == kindid && m.RootCode == roleid && m.IsDel == false).FirstOrDefault();
                    //根据资质小类获取资质大类信息,限定角色 
                    dicBig = dbContext.Dictionary.Where(m => m.SID == dicSm.ParentSID && m.RootCode == roleid && m.IsDel == false).FirstOrDefault();
                    //根据资质关系表t_sys_dictrelation获取资质等级
                    var childIds = (from qualGrade in dbContext.Dictionary
                                    join qualRel in dbContext.DictionaryRelation on qualGrade.SID equals qualRel.ParentID
                                    where qualRel.ParentID == dicSm.SID && qualGrade.IsDel == false
                                    select qualRel.ChildID ?? 0).ToList();
                    dicLev = dbContext.Dictionary.Where(m => m.Code == q.GradeCode && childIds.Contains(m.SID) && m.IsDel == false).FirstOrDefault();
                    smValue = dicSm.Code + "@" + dicSm.SID;
                    bigValue = dicBig.Code + "@" + dicBig.SID;
                    ////资质等级可能没有 2013-11-25 毛凯
                    levValue = dicLev == null ? "" : dicLev.Code + "@" + dicLev.SID;
                    qual.dicSm = smValue;
                    qual.dicBig = bigValue;
                    qual.dicLev = levValue;
                }
            }
            catch (Exception e)
            {

            }
            return qual;
        }
        /// <summary>
        /// 根据roleid或者企业classid获取企业应该具有的资质列表
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="classid"></param>
        /// <returns></returns>
        public override List<DTO.CorpKindKeyAndValue> GetCorpQualTypesByUserGuid(int roleid, int classid, string areaCode)
        {
            string classkind = "";
            switch (roleid)
            {
                case 15:
                    classkind = "1000";
                    break;
                case 105:
                    classkind = "1105";
                    break;
                case 42:
                    classkind = "1021";
                    break;
                case 45:
                    classkind = "1045";
                    break;
                case 46:
                    classkind = "1046";
                    break;
                case 47:
                    classkind = "1047";
                    break;
                case 48:
                    classkind = "1048";
                    break;
                case 30://混凝土
                case 31://预制件
                    classkind = "3030";
                    break;

                default:
                    break;
            }
            switch (classid)
            {
                case 2501:
                    classkind = "1000";
                    break;
                case 8010:
                    classkind = "1105";
                    break;
                case 2502:
                    classkind = "1021";
                    break;
                case 2505:
                    classkind = "1045";
                    break;
                case 2508:
                    classkind = "1048";
                    break;
                case 2506:
                    classkind = "1046";
                    break;
                case 2507:
                    classkind = "1047";
                    break;
                case 2500:
                    classkind = "1046";
                    break;
                case 30://混凝土
                case 31://预制件
                    classkind = "3030";
                    break;

                default:
                    break;
            }
            List<DTO.CorpKindKeyAndValue> list = new List<DTO.CorpKindKeyAndValue>();
            try
            {
                list = (from c in dbContext.CorpKind
                        where c.ClassKind == classkind
                        select new DTO.CorpKindKeyAndValue { ID = c.ID, Title = c.Title, SubTitle = c.SubTitle }).OrderByDescending(c => c.Title.Contains("施工总承包")).ThenByDescending(c => c.Title.Contains("专业承包")).ToList();
            }
            catch { }
            return list;
        }
        #endregion UC控件调用

        #region 字典相关的功能

        public override string GetDictionary(string type, string condition, string areaCode)
        {
            Dictionary<string, string> dicResult = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(condition) && StringHelper.SqlFilter(condition))
            {
                dicResult.Add("错误", "查询条件包含非法字符!");
            }
            else
            {
                GetDictionaryInternal(type, condition, out dicResult);
            }

            return JsonConvert.SerializeObject(dicResult);
        }

        /// <summary>
        /// 查询字典。
        /// </summary>
        /// <param name="type"></param>
        /// <param name="condition"></param>
        /// <param name="dicResult"></param>
        private void GetDictionaryInternal(string type, string condition, out Dictionary<string, string> dicResult)
        {
            DictionaryDALWh dicDal = new DictionaryDALWh();
            dicResult = new Dictionary<string, string>();
            IList<KeyValue> listKv = new List<KeyValue>();
            string sql = string.Empty;
            switch (type.ToLower())
            {
                case "area":    ////查询市信息。
                    listKv = dicDal.GetCity(condition);
                    break;
                case "areasub":         ////查询区信息。
                    listKv = dicDal.GetDistrict(condition);
                    break;
                case "areassq":
                    listKv = dicDal.GetAreaSSQ(condition);
                    break;
                case "corptype":        ////查询企业类型。
                    listKv = dicDal.GetCorpType(condition);
                    break;
                case "empdegree":       ////查询文化程度。
                    listKv = dicDal.GetEmpDegreeType(condition);
                    break;
                case "empmajor":        ////查询人员所学专业。
                    listKv = dicDal.GetDic("major");
                    break;
                case "empsex":        ////查询人员性别。
                    listKv = dicDal.GetDic("Sex");
                    break;
                case "empjobstatus":        ////查询人员在职状态。
                    listKv = dicDal.GetDic("JobAs");
                    break;
                case "corpusertype":        ////查询人员在职状态。
                    listKv = dicDal.GetDic("CorpUserType");
                    break;
                case "zjzy":        ////查询人员在职状态。
                    listKv = dicDal.GetDic("ZJZY");
                    break;
                case "empzctitle":
                    listKv = dicDal.GetDic("EmpZCTitle");
                    break;
                case "wdrqcradetitle":
                    listKv = dicDal.GetDic("wdrqCradeTitle");
                    break;
                case "dutylevel":
                    listKv = dicDal.GetDic("DutyLevel");
                    break;
                case "certificatetype": ////身份证件类型
                    listKv = dicDal.GetDic("certificatetype");
                    break;
                case "post":        ////评审资格1.
                    listKv = dicDal.GetPost();
                    break;
                case "postsub":     ////评审资格2.
                    listKv = dicDal.GetPost1(condition);
                    break;
                case "machineisown":     ////自有或租赁
                    listKv = dicDal.GetDic("machineisown");
                    break;
                default:
                    var query = from dict in dbContext.Dictionary
                                where dict.RootCode == type && dict.IsDel == false && dict.IsDisplay == true
                                select new KeyValue
                                {
                                    Key = dict.Code,
                                    Value = dict.Name
                                };
                    listKv = query.ToList();
                    break;
            }
            try
            {
                foreach (KeyValue kv in listKv)
                {
                    if (!dicResult.Keys.Contains(kv.Key))
                        dicResult.Add(kv.Key, kv.Value);
                }
            }
            catch (Exception ex)
            {
                dicResult.Clear();
                dicResult.Add("错误", ex.Message);
            }
        }

        public override IList<DTO.DictQualityInfo> GetQualitiesDic(string rootCode, string parentId)
        {
            int parentid = 0;
            int.TryParse(parentId, out parentid);
            var dbDict = dbContext.Dictionary;
            var query = from dict in dbDict
                        where dict.IsDel == false && dict.ParentSID == parentid && dict.RootCode == rootCode
                        orderby dict.SortValue ascending
                        select new DTO.DictQualityInfo()
                        {
                            Id = dict.SID,
                            Code = dict.Code,
                            Title = dict.Name
                        };

            var result = query.ToList();
            if (result.Count == 0)
            {
                var dbDictRelation = dbContext.DictionaryRelation;
                var query1 = from dictRel in dbDictRelation
                             where dictRel.ParentID == parentid
                             select dictRel.ChildID ?? 0;
                IList<int> childIds = query1.ToList();
                query = from dict in dbDict
                        where dict.IsDel == false && childIds.Contains(dict.SID) && dict.RootCode == rootCode
                        orderby dict.SortValue ascending
                        select new DTO.DictQualityInfo()
                        {
                            Id = dict.SID,
                            Code = dict.Code,
                            Title = dict.Name
                        };
                result = query.ToList();
            }
            return result;
        }

        public override IList<DTO.DictQualityInfo> GetQualitiesDicAll(string rootCode, string parentId, string childRootCode)
        {
            int parentid = 0;
            int.TryParse(parentId, out parentid);
            //取得资质资格
            var dbDict = dbContext.Dictionary;

            if (string.IsNullOrEmpty(childRootCode))
            {
                var query = from dict in dbDict
                            where dict.IsDel == false && dict.ParentSID == parentid && dict.RootCode == rootCode
                            orderby dict.SortValue ascending
                            select new DTO.DictQualityInfo()
                            {
                                Id = dict.SID,
                                Code = dict.Code,
                                Title = dict.Name,
                                Pid = dict.ParentSID
                            };
                return query.ToList();
            }
            //取得全部资格等级（二级数据）
            //var parentIds = result.Select(t => t.Id).ToList();
            var dbDictRelation = dbContext.DictionaryRelation;
            var query1 = from dictRel in dbDictRelation
                         join dict in dbDict on dictRel.ChildID equals dict.SID
                         where dictRel.ParentID == parentid && dict.RootCode == childRootCode
                         orderby dict.SortValue ascending
                         select new DTO.DictQualityInfo()
                         {
                             Id = dict.SID,
                             Code = dict.Code,
                             Title = dict.Name,
                             Pid = dictRel.ParentID ?? 0
                         };

            return query1.ToList();
            // return result.Union(result1).ToList();
        }
        public override string GetQualityTitle(string rootCode, string code)
        {
            return base.GetQualityTitle(rootCode, code);
        }

        public override List<DTO.T_Sys_FuncPageMapping> GetFuncPageMapping(string appId)
        {
            List<DTO.T_Sys_FuncPageMapping> mappings = new List<DTO.T_Sys_FuncPageMapping>();
            var query = from mapping in dbContext.FuncPageMapping
                        where mapping.AppId == appId
                        select mapping;
            var result = query.ToList();
            var pageCodes = result.Select(r => r.PageCode.ToLower()).Distinct();
            foreach (string pageCode in pageCodes)
            {
                DTO.T_Sys_FuncPageMapping m = new DTO.T_Sys_FuncPageMapping();
                m.PageCode = pageCode.ToLower();
                m.FuncCodes = result.Where(r => r.PageCode.ToLower() == pageCode).Select(r1 => r1.FuncCode.ToLower()).ToList();
                mappings.Add(m);
            }
            return mappings;
        }

        #endregion

        #region 地区控件调用
        /// <summary>
        /// 获取市级
        /// </summary>
        /// <returns></returns>
        public override List<DTO.a_AreaInfo> GetCity()
        {
            var query = from areainfo in dbContext.AreaInfo
                        where areainfo.Code != "00"
                        orderby areainfo.sortIndex
                        select areainfo;
            List<a_AreaInfo_Zbdl> list = query.ToList();
            List<DTO.a_AreaInfo> lists = new List<DTO.a_AreaInfo>();
            foreach (a_AreaInfo_Zbdl item in list)
            {
                DTO.a_AreaInfo area = new DTO.a_AreaInfo();
                EntityHelper.ConvertEntity2OtherEntity(item, area);
                lists.Add(area);
            }
            return lists;
        }

        /// <summary>
        /// 获取区级
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public override List<DTO.a_AreaSubInfo> GetQu(string code)
        {
            var query = dbContext.AreaSubInfo.Where(m => m.Code == code).OrderBy(m => m.CodeForSort);
            List<a_AreaSubInfo_Zbdl> list = query.ToList();
            List<DTO.a_AreaSubInfo> lists = new List<DTO.a_AreaSubInfo>();
            foreach (a_AreaSubInfo_Zbdl item in list)
            {
                DTO.a_AreaSubInfo area = new DTO.a_AreaSubInfo();
                EntityHelper.ConvertEntity2OtherEntity(item, area);
                lists.Add(area);
            }
            return lists;
        }

        /// <summary>
        /// 根据区级code获得地址
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public override string GetAddress(string code)
        {
            var query1 = from areasub in dbContext.AreaSubInfo
                         join areainfo in dbContext.AreaInfo on areasub.Code equals areainfo.Code
                         where areasub.SortCode == code
                         select areainfo.Title + areasub.Title;
            var query2 = from areainfo in dbContext.AreaInfo
                         where areainfo.Code == code
                         select areainfo.Title;
            return code.Length == 4 ? query1.FirstOrDefault() : query2.FirstOrDefault();
        }
        #endregion

        public override Fly.Common.WorkFlow.FlowResult GetNextFlowCode(string roleId, string manager, string areaCode, string classId, string flowCode, Fly.Common.WorkFlow.OptType optType)
        {
            var nextNode = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(roleId, manager, areaCode.Length > 2 ? areaCode.Substring(0, 2) : areaCode, classId, flowCode, optType);
            return nextNode;
        }

        public override string GetFlowCodeTitle(string areaCode, string classId, string flowCode)
        {
            var title = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(areaCode, classId, flowCode);
            return title;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="newPwd"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override bool ResetPassword(Guid userGuid, string newPwd, string areaCode)
        {
            bool rst = false;
            var user = dbContext.T_Sys_Users.Where(r => r.UserGuid == userGuid).FirstOrDefault();
            if (user != null)
            {
                try
                {
                    user.Pwd = newPwd;
                    user.Password = MD5Helper.MD5WebEncryptCode(newPwd);
                    dbContext.SaveChanges();
                    rst = true;
                }
                catch (Exception ex)
                {

                }
            }

            return rst;
        }

        /// <summary>
        /// 重置组织机构代码
        /// </summary>
        /// <param name="userGuid"></param>
        /// <param name="newPwd"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override bool ResetOrginazationCode(Guid userGuid, string newCode, string areaCode)
        {
            bool rst = false;
            var user = dbContext.T_Sys_Users.Where(r => r.UserGuid == userGuid).FirstOrDefault();
            if (user != null)
            {
                try
                {
                    user.ZZJGDM = newCode;
                    user.Pwd = newCode;
                    user.Password = MD5Helper.MD5WebEncryptCode(newCode);
                    dbContext.SaveChanges();
                    rst = true;
                }
                catch (Exception ex)
                {

                }
            }

            var corp = dbContext.Corp_CompanyInfos.Where(r => r.CorpUserGuid == userGuid &&r.IsDel==false).FirstOrDefault();

            if (corp != null)
            {
                corp.OrginazationCode = newCode;               
                dbContext.SaveChanges();
                rst = true;
            }
           
            ////记录登录日志。
            UserLogManager.Log(new User_Log()
            {
                Content = "用户修改组织机构编码",
                ObjectId = userGuid.ToString(),
                IsrtUser = userGuid.ToString(),
                IsrtUserName =""
            });
            return rst;
        }


        #region 获取变更列表 2013-11-4 毛凯
        public override string GetChangeRecords(string condition,
            int pageNum,
            int pageSize,
            string areaCode)
        {
            List<DTO.QueryChangeInfoCondition> conList = JsonConvert.DeserializeObject<List<DTO.QueryChangeInfoCondition>>(condition);
            var dbChangeInfo = dbContext.ChangeSetInfo;
            var query = from change in dbChangeInfo
                        where (change.IsDel == false || change.IsDel == null) && change.AreaCode.StartsWith(areaCode)
                        select change;
            if (conList != null && conList.Count > 0)
            {
                query = query.BuildCondition<V_ChangeInfoEx>(conList);
            }
            if (true)
            {


            }
            var result = query.OrderByDescending(o => o.ChangeSetId).Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            List<DTO.V_ChangeInfo> list = new List<DTO.V_ChangeInfo>();
            foreach (var item in result)
            {
                DTO.V_ChangeInfo dtoItem = new DTO.V_ChangeInfo();
                EntityHelper.ConvertEntity2OtherEntity(item, dtoItem);
                dtoItem.StrFlowCode = Fly.Common.WorkFlow.FlowHelper.GetFlowCodeTitle(
                    areaCode,
                    "8020",
                    item.FlowCode);
                list.Add(dtoItem);
            }
            return JsonConvert.SerializeObject(list);
        }

        public override int GetChangeRecordsCount(string condition, string areaCode)
        {
            List<DTO.QueryChangeInfoCondition> conList = JsonConvert.DeserializeObject<List<DTO.QueryChangeInfoCondition>>(condition);
            var dbChangeInfo = dbContext.ChangeSetInfo;
            var query = from change in dbChangeInfo
                        where (change.IsDel == false || change.IsDel == null) && change.AreaCode.StartsWith(areaCode)
                        select change;
            if (conList != null && conList.Count > 0)
            {
                query = query.BuildCondition<V_ChangeInfoEx>(conList);
            }
            var result = query.Count();
            return result;
        }
        #endregion

        /// <summary>
        /// 取得统计--企业和人员类型
        /// </summary>
        /// <param name="rootCode"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetSysStaticSettings(string rootCode, string areaCode)
        {
            //取得当前地区统计类型的设置
            var query = (from setting in dbContext.T_Sys_StaticSettings
                         where setting.AreaCode == areaCode && setting.RootCode == rootCode && setting.IsDel == false
                         select new
                         {
                             setting.ClassId,
                             setting.ClassName
                         }).ToDictionary(p => p.ClassId, p => p.ClassName);
            //不存在取默认类型
            if (query.Count() == 0)
            {
                var query1 = (from setting in dbContext.T_Sys_StaticSettings
                              where setting.AreaCode == "00" && setting.RootCode == rootCode && setting.IsDel == false
                              select new
                              {
                                  setting.ClassId,
                                  setting.ClassName
                              }).ToDictionary(p => p.ClassId, p => p.ClassName);
                return JsonConvert.SerializeObject(query1);
            }
            return JsonConvert.SerializeObject(query);
        }

        #region 根据用户角色获取所有状态
        public override string GetAllFlowStatus(string areaCode, string roleId, string classId, out string msg)
        {
            var result = Fly.Common.WorkFlow.FlowHelper.GetAllStatusFlowCodes2(roleId, areaCode, classId, out msg);
            if (result == null)
            {
                return null;
            }
            result = result.OrderBy(f => f.Key).ToDictionary(f => f.Key, f => f.Value);
            ////将操作进行翻译
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var key in result.Keys)
            {
                string newKey = "";
                switch (key)
                {
                    case "5":
                        newKey = "处理中";
                        break;
                    case "6":
                        newKey = "退回";
                        break;
                    case "7":
                        newKey = "完成";
                        break;
                    default:
                        break;
                }
                if (!string.IsNullOrEmpty(newKey))
                {
                    dic.Add(newKey, result[key]);
                }
            }
            return JsonConvert.SerializeObject(dic);
        }

        public override string GetAllStatusFlowCodesByTitle(string roleID, string areaCode, string classId, out string msg)
        {
            var result = Fly.Common.WorkFlow.FlowHelper.GetAllStatusFlowCodesByTitle2(roleID, areaCode, classId, out msg);
            return JsonConvert.SerializeObject(result);
        }

        public override string GetAllBusinessStatusAndProcessing(string roleID, string areaCode, string classId, out string msg, bool contiansAll = false)
        {
            var result = Fly.Common.WorkFlow.FlowHelper.GetAllBusinessStatusAndProcessing(roleID, areaCode, classId, out msg, contiansAll);
            return JsonConvert.SerializeObject(result);
        }

        public override string GetAllBusinessStatus(string areaCode, string classId, out string msg)
        {
            var result = Fly.Common.WorkFlow.FlowHelper.GetAllBusinessStatus(areaCode, classId, out msg);
            return JsonConvert.SerializeObject(result);
        }

        public override int CheckCreater(string areaCode, string classId, string roleID, out string msg)
        {
            int result = Fly.Common.WorkFlow.FlowHelper.CheckCreater(areaCode, classId, roleID, out msg);
            return result;
        }
        #endregion

        public override bool IsAppRightValid(int AppID, Guid UserGuid)
        {
            try
            {
                var query = (from apps in dbContext.SysApp
                             join funcs in dbContext.SysFuncPermission
                             on apps.KeyGuid equals funcs.FunctionGuid
                             where apps.AppId == AppID && funcs.ObjectGuid == UserGuid
                             select new { apps.AppId });
                return query.Count() > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 根据地区编号取得地区名称
        /// </summary>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetAreaCodeTitle(string areaCode)
        {
            if (areaCode.Trim().Length == 2)
            {
                return dbContext.AreaInfo.Where(a => a.Code == areaCode).Select(p => p.Title).FirstOrDefault();
            }
            return dbContext.AreaSubInfo.Where(a => a.SortCode == areaCode).Select(p => p.Title).FirstOrDefault();
        }

        #region 消息推送 - 站内信

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="msg">信息</param>
        /// <returns>是否成功</returns>
        public override bool SendMsg(DTO.T_Msg_SentMsg msg)
        {
            T_Msg_SentMsg entity;
            if (!string.IsNullOrEmpty(msg.Receiver))
            {
                string[] users = msg.Receiver.Split(',');
                for (int i = 0; i < users.Length; i++)
                {
                    entity = new T_Msg_SentMsg
                    {
                        AppID = msg.AppID,
                        MsgText = msg.MsgText,
                        Sender = msg.Sender,
                        SendTime = msg.SendTime,
                        Receiver = users[i],
                        MsgType = 0,
                        Flag = 0,
                        AreaCode = msg.AreaCode
                    };
                    dbContext.Messages.Add(entity);
                    dbContext.Entry(entity).State = EntityState.Added;
                }
            }

            try
            {
                dbContext.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="Receiver">接收者</param>
        /// <param name="Sender">发送者</param>
        /// <param name="AppID">AppID</param>
        /// <param name="LastSearchTime">上次查询时间</param>
        /// <param name="IsRead">要的是已读消息？</param>
        /// <param name="DoRead">接收完之后要标志为已读？</param>
        /// <param name="AreaCode">所在地区</param>
        public override List<DTO.T_Msg_SentMsg> GetMsgs(string Receiver, string Sender, int AppID, DateTime? LastSearchTime
            , Boolean? IsRead, bool DoRead, string AreaCode)
        {
            var dbUser = dbContext.T_Sys_Users;
            var dbMsg = dbContext.Messages;
            var query = dbContext.Messages.Where(m => m.AppID == AppID && m.AreaCode == AreaCode && m.Flag == 0);

            if (IsRead != null)
            {
                query = query.Where(m => m.MsgType == ((IsRead ?? false) ? 1 : 0));
            }
            if (!string.IsNullOrEmpty(Sender))
            {
                query = query.Where(m => m.Sender == Sender);
            }
            if (!string.IsNullOrEmpty(Receiver))
            {
                Guid ug = Guid.Parse(Receiver);
                var roleID = dbUser.FirstOrDefault(u => u.UserGuid == ug).RoleID;
                string roleStr = roleID == null ? "" : roleID.ToString();
                query = query.Where(m => m.Receiver == Receiver || m.Receiver == roleStr);
            }
            if (LastSearchTime != null)
            {
                query = query.Where(m => m.SendTime >= LastSearchTime);
            }

            var newDataList = query.Select(m => new DTO.T_Msg_SentMsg
            {
                ID = m.ID,
                AppID = m.AppID,
                Flag = m.Flag,
                MsgText = m.MsgText,
                MsgType = m.MsgType,
                Receiver = m.Receiver,
                Sender = m.Sender,
                SendTime = m.SendTime
            }).OrderBy(m => m.SendTime).ToList();

            if (DoRead)
            {
                foreach (var item in query)
                {
                    item.MsgType = 1;
                }
                dbContext.SaveChanges();
            }
            return newDataList;
        }

        /// <summary>
        /// 获取站内信中可用用户列表
        /// </summary>
        /// <param name="areaCode">所在地区</param>
        /// <param name="classIds">企业类型集合</param>
        /// <param name="manageRoleIds">要获取的角色ID列表</param>
        public override string GetMsgUser(string areaCode, List<int> classIds, List<int> manageRoleIds)
        {
            var dbUser = dbContext.T_Sys_Users;
            var dbCompany = dbContext.Corp_CompanyInfos;
            var companyQuery = from user in dbUser
                               join company in dbCompany on user.UserGuid equals company.CorpUserGuid
                               where user.AreaCodeScope == areaCode && classIds.Contains((int)company.classID)
                               && !manageRoleIds.Contains((int)user.RoleID)
                               group user by new { RoleID = user.RoleID, Name = user.Name, UserGuid = user.UserGuid } into g
                               select new DTO.MsgUserInfo()
                               {
                                   Name = g.Key.Name,
                                   UserGuid = g.Key.UserGuid,
                                   RoleId = g.Key.RoleID
                               };
            var managerQuery = from user in dbUser
                               where user.AreaCodeScope == areaCode && manageRoleIds.Contains((int)user.RoleID)
                               group user by new { RoleID = user.RoleID, Name = user.Name, UserGuid = user.UserGuid } into g
                               select new DTO.MsgUserInfo()
                               {
                                   Name = g.Key.Name,
                                   UserGuid = g.Key.UserGuid,
                                   RoleId = g.Key.RoleID
                               };

            var list = managerQuery.ToList<DTO.MsgUserInfo>();
            list.AddRange(companyQuery.ToList<DTO.MsgUserInfo>());

            return JsonConvert.SerializeObject(list);
        }

        /// <summary>
        /// 逻辑删除信息
        /// </summary>
        /// <param name="CurrentUser">当前用户(只能删除自己发送的消息)</param>
        /// <param name="msgIds">消息ID的拼接字符串</param>
        public override bool MsgsDelete(string CurrentUser, int AppID, string msgIds)
        {
            string sql = String.Format("UPDATE T_Msg_SentMsg SET Flag = 1 WHERE AppID = {0} AND Sender = '{1}' AND ID IN({2})"
                , AppID, CurrentUser, msgIds);
            try
            {
                dbContext.Database.ExecuteSqlCommand(sql);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取首页上显示的简要站内信
        /// </summary>
        /// <param name="Receiver">当前登录者</param>
        /// <param name="MaxCount">最多显示多少条</param>
        /// <param name="AppID">应用编号</param>
        public override List<DTO.T_Msg_SentMsg> GetLetterBrief(string Receiver, int MaxCount, int AppID)
        {
            var query = from m in dbContext.Messages
                        where m.AppID == AppID && m.Flag == 0
                               && m.Receiver == Receiver
                        orderby m.SendTime descending
                        select m;

            var newDataList = query.Take(MaxCount).Select(m => new DTO.T_Msg_SentMsg
            {
                ID = m.ID,
                MsgText = m.MsgText,
                Receiver = m.Receiver,
                Sender = m.Sender,
                SendTime = m.SendTime
            }).ToList();


            return newDataList;
        }

        #endregion

        #region 消息推送 - 即时消息

        public override bool SendChat(DTO.T_Chat_ChatInfo chatInfo)
        {
            T_Chat_ChatInfo entity = new T_Chat_ChatInfo
            {
                AppID = chatInfo.AppID,
                MsgText = chatInfo.MsgText,
                Sender = chatInfo.Sender,
                SendTime = chatInfo.SendTime,
                Receiver = chatInfo.Receiver,
                IsDel = false,
                IsRead = false,
                AreaCode = chatInfo.AreaCode
            };
            dbContext.ChatInfos.Add(entity);
            dbContext.Entry(entity).State = EntityState.Added;

            try
            {
                dbContext.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public override List<DTO.T_Chat_ChatInfo> GetChatInfos(string Receiver, string Sender, int AppID, DateTime? LastSearchTime
            , Boolean? IsRead, bool DoRead, string AreaCode)
        {
            var dbUser = dbContext.T_Sys_Users;
            var dbChat = dbContext.ChatInfos;
            var query = dbContext.ChatInfos.Where(c => c.AppID == AppID && c.AreaCode == AreaCode && !c.IsDel);

            if (IsRead != null)
            {
                query = query.Where(m => m.IsRead == IsRead);
            }
            if (!string.IsNullOrEmpty(Sender))
            {
                query = query.Where(m => m.Sender == Sender);
            }
            if (!string.IsNullOrEmpty(Receiver))
            {
                //Guid ug = Guid.Parse(Receiver);
                //var roleID = dbUser.FirstOrDefault(u => u.UserGuid == ug).RoleID;
                //string roleStr = roleID == null ? "" : roleID.ToString();
                //query = query.Where(m => m.Receiver == Receiver || m.Receiver == roleStr);
                query = query.Where(m => m.Receiver == Receiver);
            }
            if (LastSearchTime != null)
            {
                query = query.Where(m => m.SendTime >= LastSearchTime);
            }

            var newDataList = query.Select(m => new DTO.T_Chat_ChatInfo
            {
                ID = m.ID,
                AppID = m.AppID,
                MsgText = m.MsgText,
                IsRead = m.IsRead,
                Receiver = m.Receiver,
                Sender = m.Sender,
                SendTime = m.SendTime
            }).OrderBy(m => m.SendTime).ToList();

            if (DoRead)
            {
                foreach (var item in query)
                {
                    item.IsRead = true;
                }
                dbContext.SaveChanges();
            }
            return newDataList;
        }

        public override List<DTO.T_Chat_ChatInfo> GetChatHistory(string Receiver, string Sender, int AppID, DateTime? StartTime
            , DateTime? EndTime, string AreaCode)
        {
            var dbChat = dbContext.ChatInfos;
            var query = dbChat.Where(c => c.AppID == AppID && c.AreaCode == AreaCode && !c.IsDel
                && ((c.Receiver == Receiver && c.Sender == Sender) || (c.Receiver == Sender && c.Sender == Receiver)));

            if (StartTime != null)
            {
                query = query.Where(c => c.SendTime >= StartTime);
            }
            if (EndTime != null)
            {
                query = query.Where(c => c.SendTime <= EndTime);
            }

            var historyList = query.Select(m => new DTO.T_Chat_ChatInfo
            {
                ID = m.ID,
                AppID = m.AppID,
                MsgText = m.MsgText,
                IsRead = true,
                Receiver = m.Receiver,
                Sender = m.Sender,
                SendTime = m.SendTime
            }).OrderBy(m => m.SendTime).ToList();

            return historyList;
        }

        public override List<DTO.T_Chat_ChatInfo> GetChatBrief(string Receiver, int MaxCount, int AppID)
        {
            return null;
        }

        #endregion

        /// <summary>
        /// 验证用户信息，2014-1-26 添加烟台无key用户不允许登陆
        /// 若需要添加其他验证，也可在此处进行补充
        /// </summary>
        /// <param name="user"></param>
        /// <param name="appid"></param>
        /// <returns></returns>
        private UserInfo CheckUserInfo(UserInfo user, string appid, bool allowNoKeyUser)
        {
            if (!allowNoKeyUser)
            {
                ////无key用户不允许登陆的验证
                if (!string.IsNullOrEmpty(user.DogId))
                {
                    int dogid = -1;
                    if (int.TryParse(user.DogId, out dogid))
                    {
                        if (dogid <= 0)
                        {
                            user.Result = false;
                            user.Message = "尚未办理数字证书设备，办理后请插入对应的设备进行登陆";
                        }
                    }
                }
                else
                {
                    user.Result = false;
                    user.Message = "尚未办理数字证书设备，办理后请插入对应的设备进行登陆";
                }
            }
            return user;
        }

        public override IList<DTO.T_Sys_Dict> GetSysDicts(string rootCode, string parentSID)
        {
            if (string.IsNullOrEmpty(rootCode))
            {
                return null;
            }
            var query = from dict in dbContext.Dictionary
                        where dict.RootCode == rootCode && dict.IsDel == false && dict.IsDisplay == true
                        select new DTO.T_Sys_Dict
                        {
                            SID = dict.SID,
                            Code = dict.Code,
                            Description = dict.Description,
                            Name = dict.Name,
                            ParentSID = dict.ParentSID,
                            RootCode = dict.RootCode,
                            SortValue = dict.SortValue
                        };
            if (!string.IsNullOrEmpty(parentSID))
            {
                int sid = 0;
                if (int.TryParse(parentSID, out sid))
                {
                    query = query.Where(o => o.ParentSID == sid);
                }
            }
            var result = query.ToList();
            return result;
        }

        #region 专家登录
        public override UserInfo DoExpertLogin(string idNum, string passWord, string appId)
        {
            var dbUser = dbContext.T_Sys_Users;
            var dbEmp = dbContext.Emp_Manager;
            UserInfo userInfo = new UserInfo();
            if ((!string.IsNullOrEmpty(idNum)) && (!string.IsNullOrEmpty(passWord)))
            {
                try
                {
                    var query = from users in dbUser
                                join experts in dbEmp on users.UserGuid equals experts.EmpGuid
                                where experts.IDCard != null && experts.IDCard == idNum && users.Pwd.ToUpper() == passWord.ToUpper()
                                select users;
                    var user = query.FirstOrDefault();
                    if (user != null)
                    {
                        userInfo = GetUserModel(user, true);
                        userInfo = InitUserAuthority(userInfo, appId);
                        userInfo.Result = true;
                        userInfo.Message = "登录成功";
                        ////记录登录日志。
                        UserLogManager.Log(new User_Log()
                        {
                            Content = "用户[" + userInfo.UserName + "]登录",
                            ObjectId = userInfo.UserGuid,
                            IsrtUser = userInfo.UserGuid,
                            IsrtUserName = userInfo.UserName
                        });
                    }
                    else
                    {
                        userInfo.Result = false;
                        userInfo.Message = "登录失败！身份证号码、或密码有误！";
                    }
                }
                catch (Exception ex)
                {
                    userInfo.Result = false;
                    userInfo.Message = ex.Message;
                }
            }
            else
            {
                userInfo.Result = false;
                userInfo.Message = "登录失败！身份证号码或密码不能为空";
            }
            return userInfo;
        }
        #endregion

        #region 专家分库
        /// <summary>
        /// 获取分库信息
        /// </summary>
        /// <returns></returns>
        public override List<DTO.T_Sys_Dict> GetExpertDBList()
        {
            var query = from dict in dbContext.Dictionary
                        where dict.RootCode == "EXPERTDBCODE" && dict.IsDel == false
                        orderby dict.SortValue
                        select dict;
            List<T_Sys_Dict_Zbdlry> list = query.ToList();
            List<DTO.T_Sys_Dict> lists = new List<DTO.T_Sys_Dict>();
            foreach (T_Sys_Dict_Zbdlry item in list)
            {
                DTO.T_Sys_Dict dic = new DTO.T_Sys_Dict();
                EntityHelper.ConvertEntity2OtherEntity(item, dic);
                lists.Add(dic);
            }
            return lists;
        }

        /// <summary>
        /// 根据code获得Name
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public override string GetExpertDBName(string code)
        {
            var query = from dict in dbContext.Dictionary
                        where dict.RootCode == "EXPERTDBCODE" && dict.IsDel == false && dict.Code == code
                        orderby dict.SortValue
                        select dict.Name;
            return query.FirstOrDefault();
        }
        #endregion

        /// <summary>
        /// 专家页面 通过手机号重置密码
        /// </summary>
        public override bool ResetPwdByTel(string phoneNum, string newPwd)
        {
            var ems = dbContext.Emp_Manager;
            var users = dbContext.T_Sys_Users;
            var user = (from m in ems
                        join u in users
                        on m.EmpGuid equals u.UserGuid
                        where m.MobileTel == phoneNum
                        select u).FirstOrDefault();

            if (user == null)
            {
                return false;
            }

            user.Pwd = newPwd;
            try
            {
                dbContext.SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }
        ///// <summary>
        ///// 获取企业或者人员的审核流程
        ///// </summary>
        ///// <param name="objectid"></param>
        ///// <param name="type"></param>
        ///// <returns></returns>
        //public string GetClassIDbyGuid(string objectID, string type)
        //{
        //    string dictRootCode = string.Empty;
        //    switch (type.ToLower())
        //    { 
        //        case "basic":
        //            dictRootCode = "roleclassid";
        //            break;
        //        case "change":
        //            dictRootCode = "roleclassidchange";
        //            break;
        //        default:
        //            dictRootCode = "roleclassid";
        //            break;
        //    }
        //    Dictionary<string, string> dicResult = new Dictionary<string, string>();
        //    GetDictionaryInternal(dictRootCode, "", out dicResult);
        //    int roleID = this.GetRoleIDbyGuid(objectID);
        //    if(dicResult!=null&&dicResult.ContainsKey(roleID.ToString()))
        //    {
        //        return dicResult[roleID.ToString()];
        //    }
        //    return null;
        //}
        ///// <summary>
        ///// 根据企业或者人员的Guid获取所在企业RoleID
        ///// </summary>
        ///// <param name="objectid"></param>
        ///// <returns></returns>
        //private int GetRoleIDbyGuid(string objectid)
        //{
        //    int roleID = 0;
        //    EnterpriseDALWh _dal = new EnterpriseDALWh();
        //    roleID=_dal.GetRoleIDbyGuid(objectid);
        //    return roleID;
        //}

        #region 新变更方法

        /// <summary>
        /// 取得变更项选择下拉列表
        /// </summary>
        /// <param name="changeType"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetChangeItemsNew(string changeType, int parentId, string appId, string areaCode)
        {
            IList<Tb_ChangeItemEx> items = null;
            string[] types = changeType.Split(',');
            List<int> itemTypeArray = new List<int>();
            int itemType = 0;
            ////转化变更类型
            foreach (string str in types)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    if (int.TryParse(str, out itemType))
                    {
                        itemTypeArray.Add(itemType);
                    }
                }
            }
            ////取变更项集合
            if (itemTypeArray.Count > 0)
            {
                items = dbContext.ChangeItems.Where(c => itemTypeArray.Contains(c.ItemType ?? 0) && c.IsDel != true && c.ClassID == 8020 && c.AppId == appId.Trim() && c.ParentId == parentId).OrderBy(c => c.SortCode).ToList();
                if (items == null || items.Count == 0)
                {
                    items = dbContext.ChangeItems.Where(c => itemTypeArray.Contains(c.ItemType ?? 0) && c.IsDel != true && c.ClassID == 8020 && c.AppId == "0" && c.ParentId == parentId).OrderBy(c => c.SortCode).ToList();
                }
            }
            List<DTO.Tb_ChangeItem> list_D = new List<DTO.Tb_ChangeItem>();
            if (items != null)
            {
                ////实体转换
                foreach (Tb_ChangeItemEx item in items)
                {
                    DTO.Tb_ChangeItem item_D = new DTO.Tb_ChangeItem();
                    EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                    list_D.Add(item_D);
                }
            }
            return JsonConvert.SerializeObject(list_D);
        }

        /// <summary>
        /// 取得变更内容列表，多项变更列表
        /// </summary>
        /// <param name="changItemId"></param>
        /// <returns></returns>
        public override DTO.OperationResult GetChangItemsValues(string changItemId, string objectId, string areaCode)
        {
            Guid objGuid = Guid.Empty;
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            if (!Guid.TryParse(objectId, out objGuid))
            {
                result.Result = false;
                result.Message = "变更信息主要关键字不正确！";
                return result;
            }
            int changId = 0;
            if (!int.TryParse(changItemId, out changId))
            {
                result.Result = false;
                result.Message = "变更项关键字信息不正确！";
                return result;
            }
            ////取得变更项记录
            var changeItemCount = dbContext.ChangeItems.Where(c => c.ParentId == changId && c.IsDel != true).Count();
            if (changeItemCount > 0)
            {
                ////多条记录返回记录列表
                var changeItems = GetBindChangeValueNew(changItemId, areaCode, new string[] { objectId });
                if (changeItems != null && changeItems.Count > 0)
                {
                    result.ReturnValue = changeItems;
                }
            }
            return result;
        }

        /// <summary>
        /// 取得变更集及其包含的变更项
        /// </summary>
        /// <param name="changeSetId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetChangeDetailsNew(int changeSetId, string areaCode)
        {
            Tb_ChangeSetRecordEx changeSetInfo = dbContext.ChangeSetRecords.SingleOrDefault(cs => cs.Id == changeSetId && (cs.IsDel == false || cs.IsDel == null));
            if (changeSetInfo == null)
            {
                return "";
            }
            IList<Tb_ChangeRecordEx> changeInfos = dbContext.ChangeRecords.Where(c => c.ChangeSetId == changeSetId).ToList();
            ChangeDetailEx changeDetail = new ChangeDetailEx();
            changeDetail.ChangeSet = changeSetInfo;
            changeDetail.ChangeInfos = changeInfos;
            return JsonConvert.SerializeObject(changeDetail);
        }

        /// <summary>
        /// 根据id或父id取得一级变更项或二级变更项列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="id"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override string GetChangeItemsForIDNew(int id, string areaCode)
        {
            IList<Tb_ChangeItemEx> items = null;
            int? classValue = dbContext.ChangeItems.Where(c => c.ID == id && c.IsDel != true).Select(c => c.ClassValue).FirstOrDefault();
            ////取变更项集合
            if (classValue > 0)
            {
                /////没有子变更项
                items = dbContext.ChangeItems.Where(c => c.ID == id && c.IsDel != true).OrderBy(c => c.SortCode).ToList();
            }
            else
            {
                ////取二级变更项
                items = dbContext.ChangeItems.Where(c => c.IsDel != true && c.ClassID == 8020 && c.ParentId == id).OrderBy(c => c.SortCode).ToList();
            }
            List<DTO.Tb_ChangeItem> list_D = new List<DTO.Tb_ChangeItem>();
            if (items != null)
            {
                ////实体转换
                foreach (Tb_ChangeItemEx item in items)
                {
                    DTO.Tb_ChangeItem item_D = new DTO.Tb_ChangeItem();
                    EntityHelper.ConvertEntity2OtherEntity(item, item_D);
                    list_D.Add(item_D);
                }
            }
            return JsonConvert.SerializeObject(list_D);
        }

        /// <summary>
        /// 取得变更前值
        /// </summary>
        /// <param name="changeItem"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override string GetBeforeChangeValueNew(string changeItemId, string areaCode, params string[] parameters)
        {
            if (StringHelper.SqlFilter(parameters))
            {
                return null;
            }
            int id = 0;
            int.TryParse(changeItemId, out id);
            Tb_ChangeItemEx cItem = dbContext.ChangeItems.Where(c => c.ID == id && (c.IsDel == false || c.IsDel == null)).FirstOrDefault();

            if (cItem == null)
            {
                return null;
            }
            string strSql = string.Format(cItem.BeforeSQL, parameters);
            List<KeyValue> result = dbContext.Database.SqlQuery<KeyValue>(strSql).ToList();
            if (result.Count > 0)
            {
                Dictionary<string, string> dicValue = new Dictionary<string, string>();
                dicValue.Add(result[0].Key ?? string.Empty, result[0].Value ?? string.Empty);
                return JsonConvert.SerializeObject(dicValue);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 取得变更选择数据源值
        /// </summary>
        /// <param name="changeItem"></param>
        /// <param name="appId"></param>
        /// <param name="areaCode"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override Dictionary<string, string> GetBindChangeValueNew(string changeItemId, string areaCode, params string[] parameters)
        {
            if (StringHelper.SqlFilter(parameters))
            {
                return null;
            }
            int id = 0;
            int.TryParse(changeItemId, out id);
            Tb_ChangeItemEx cItem = dbContext.ChangeItems.Where(c => c.ID == id && (c.IsDel != true || c.IsDel == null)).FirstOrDefault();

            if (cItem == null)
            {
                return null;
            }
            if (string.IsNullOrEmpty(cItem.BindSQL) || cItem.BindSQL.Length < 1)
            {
                return null;
            }
            string strSql = string.Empty;
            if (parameters == null || parameters.Length == 0)
            {
                strSql = cItem.BindSQL;
            }
            else
            {
                strSql = string.Format(cItem.BindSQL, parameters);
            }
            List<KeyValue> result = dbContext.Database.SqlQuery<KeyValue>(strSql).ToList();
            if (result.Count > 0)
            {
                Dictionary<string, string> dicValue = new Dictionary<string, string>();
                foreach (KeyValue kv in result)
                {
                    if (dicValue.Keys.Contains(kv.Key))
                    {
                        continue;
                    }
                    dicValue.Add(kv.Key, kv.Value);
                }
                return dicValue;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 添加变更申请
        /// </summary>
        /// <param name="changeInfo"></param>
        /// <returns></returns>
        public override DTO.OperationResult AddChangeNew(string changeSetInfo, string changeInfo, int codeType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            if (string.IsNullOrEmpty(changeInfo) || string.IsNullOrEmpty(changeSetInfo))
            {
                result.Message = "变更信息不完善,不能执行变更！";
                result.Result = false;
                return result;
            }
            Tb_ChangeSetRecordEx changeSet = JsonConvert.DeserializeObject<Tb_ChangeSetRecordEx>(changeSetInfo);
            ////判断企业或人员是否已审核通过
            int flowCount = dbContext.FlowCodes.Where(f => f.ObjectId == changeSet.ObjectId && areaCode.StartsWith(f.AreaCode) && f.IsDel == false && f.FlowCode.StartsWith("1,")).Count();
            if (flowCount == 0)
            {
                result.Message = "待变更企业或人员的信息尚未通过审核，不能进行变更操作！";
                result.Result = false;
                return result;
            }
            ////按变更类型ItemType判断同一类型是否存在未审核的变更。changeSet.ObjectType的值类型1,2,3,

            if (!string.IsNullOrEmpty(changeSet.ObjectType))
            {
                foreach (string itemType in changeSet.ObjectType.Split(','))
                {
                    if (itemType.Trim() == "")
                    {
                        continue;
                    }
                    var changeSetCount = dbContext.ChangeSetInfo.Where(cs => cs.ObjectType.Contains(itemType + ",") && (cs.IsDel == false || cs.IsDel == null)
                                            && cs.ObjectId == changeSet.ObjectId && !cs.FlowCode.StartsWith("1,")).Count();
                    if (changeSetCount > 0)
                    {
                        result.Message = "您尚有一条未审核通过的变更记录，请先处理之前的变更申请！";
                        result.Result = false;
                        return result;
                    }
                }
            }
            ////变更记录保存
            DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
            con.Open();
            using (DbTransaction tran = con.BeginTransaction())
            {
                try
                {
                    ////1.插入变更集信息
                    dbContext.ChangeSetRecords.Add(changeSet);
                    dbContext.SaveChanges();
                    ////2.插入变更项信息
                    List<Tb_ChangeRecordEx> recList = JsonConvert.DeserializeObject<List<Tb_ChangeRecordEx>>(changeInfo);
                    foreach (Tb_ChangeRecordEx item in recList)
                    {
                        item.ChangeSetId = changeSet.Id;
                        dbContext.ChangeRecords.Add(item);
                        dbContext.SaveChanges();
                    }
                    ////3.记录审核状态。
                    ChangeFlowCodeAdd(changeSet.Id.ToString(), codeType, areaCode);
                    ////4.插入日志表。
                    SetUserLog("添加信息变更", changeSet.Id.ToString(), changeSet.IsrtUserId, changeSet.IsrtUserName, areaCode, "1", codeType.ToString());
                    tran.Commit();
                    ////5.填充返回结果。
                    result.Message = "添加变更信息成功！";
                    result.Result = true;
                    result.ReturnValue = changeSet;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    //插入日志表
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "变更添加失败：" + ex.Message;
                    result.Result = false;
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 修改变更申请
        /// </summary>
        /// <param name="changeSetInfo"></param>
        /// <param name="changeInfo"></param>
        /// <param name="userGuid"></param>
        /// <param name="userName"></param>
        /// <param name="codeType"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public override DTO.OperationResult EditChangeNew(string changeSetInfo, string changeInfo, string roleId, int codeType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            if (string.IsNullOrEmpty(changeInfo) || string.IsNullOrEmpty(changeSetInfo))
            {
                result.Message = "变更信息不完善,不能执行变更！";
                result.Result = false;
                return result;
            }
            ////取得变更集
            Tb_ChangeSetRecordEx changeSet = JsonConvert.DeserializeObject<Tb_ChangeSetRecordEx>(changeSetInfo);
            result = CheckChangeIsExist(changeSet.Id.ToString());
            if (!result.Result)
            {
                result.Message = "没有查询到有效的变更信息！";
                result.Result = false;
                return result;
            }
            Tb_ChangeSetRecordEx currentchangeSet = (Tb_ChangeSetRecordEx)result.ReturnValue;
            ////判断信息是否上报审核
            result = CheckChangeFlowCode(changeSet.Id.ToString(), 4, codeType, roleId, areaCode);
            if (!result.Result)
            {
                result.Message = "变更信息已上报审核，不能执行修改操作！";
                return result;
            }
            ////变更信息更新
            DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
            con.Open();
            using (DbTransaction tran = con.BeginTransaction())
            {
                try
                {
                    ////1.更新变更集。
                    EntityHelper.ConvertEntity2Entity<Tb_ChangeSetRecordEx>(changeSet, currentchangeSet);
                    dbContext.SaveChanges();

                    ////2.删除变更项。
                    ChangeDALWh ChangeDALWh = new ChangeDALWh(dbContext);
                    ChangeDALWh.DeleteChanges(changeSet.Id);
                    dbContext.SaveChanges();

                    ////3.添加变更项。
                    List<Tb_ChangeRecordEx> recList = JsonConvert.DeserializeObject<List<Tb_ChangeRecordEx>>(changeInfo);
                    foreach (Tb_ChangeRecordEx item in recList)
                    {
                        item.ChangeSetId = changeSet.Id;
                        item.OptDate = DateTime.Now;
                        dbContext.ChangeRecords.Add(item);
                        dbContext.SaveChanges();
                    }
                    ////5.插入日志表。
                    SetUserLog("修改信息变更", changeSet.Id.ToString(), changeSet.IsrtUserId, changeSet.IsrtUserName, areaCode, "2", codeType.ToString());
                    tran.Commit();
                    ////6.填充返回结果。
                    result.Message = "变更申请修改成功！";
                    result.Result = true;
                    result.ReturnValue = changeSet;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    //插入日志表
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "变更修改失败：" + ex.Message;
                    result.Result = false;
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 变更申请上报
        /// </summary>
        /// <param name="changeIds"></param>
        /// <returns></returns>
        public override DTO.OperationResult SubmitChangeNew(string changeIds, string changeSetInfo, string changeInfo,
           string userGuid, string userName, string roleId, int codeType, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;

            ////changeIds标识批量上报，changeSetInfo标识单条上报
            if (string.IsNullOrEmpty(changeIds) && string.IsNullOrEmpty(changeSetInfo))
            {
                result.Message = "没有找到变更记录，请至少选择一条变更记录!";
                result.Result = false;
                return result;
            }
            ////取得变更ID列表
            IList<string> changeids = new List<string>();
            if (!string.IsNullOrEmpty(changeIds))
            {
                changeids = JsonConvert.DeserializeObject<List<string>>(changeIds);
            }
            ////取得变更集信息，单条上报先更新变更集
            if (!string.IsNullOrEmpty(changeSetInfo) && !string.IsNullOrEmpty(changeInfo))
            {
                Tb_ChangeSetRecordEx changeSet = JsonConvert.DeserializeObject<Tb_ChangeSetRecordEx>(changeSetInfo);
                if (changeSet.Id > 0)
                {
                    result = EditChangeNew(changeSetInfo, changeInfo, roleId, codeType, areaCode);
                }
                else
                {
                    result = AddChangeNew(changeSetInfo, changeInfo, codeType, areaCode);
                }
                ////取得变更集ID
                if (!result.Result)
                {
                    return result;
                }
                changeSet = (Tb_ChangeSetRecordEx)result.ReturnValue;
                changeids.Add(changeSet.Id.ToString());
            }

            ////判断变更集状态并取得审核状态列表，有上报记录即返回
            Dictionary<string, string> changeFlowCodes = new Dictionary<string, string>();
            foreach (string changeId in changeids)
            {
                result = CheckChangeIsExist(changeId);
                if (!result.Result)
                {
                    result.Message = "没有查询到有效的变更信息！";
                    result.Result = false;
                    return result;
                }
                result = CheckChangeFlowCode(changeId, 4, codeType, roleId, areaCode);
                if (!result.Result)
                {
                    result.Message = "变更信息已上报审核，不能执行修改操作！";
                    return result;
                }
                ////保存变更审核状态
                changeFlowCodes.Add(changeId, result.ReturnValue.ToString());
            }
            if (changeFlowCodes == null)
            {
                result.Message = "没有查询到有效的变更状态信息！";
                result.Result = false;
                return result;
            }

            ////更新变更集审核状态
            DbConnection con = ((IObjectContextAdapter)dbContext).ObjectContext.Connection;
            con.Open();
            using (DbTransaction tran = con.BeginTransaction())
            {
                try
                {
                    ////1.上报更新审核状态
                    string changeIdsNew = string.Empty;
                    foreach (var changeFlowCode in changeFlowCodes)
                    {
                        ChangeFlowCodeEdit(changeFlowCode.Key.Trim(), codeType, changeFlowCode.Value.Trim(), areaCode);
                        changeIdsNew += changeFlowCode.Key.Trim() + ",";
                    }
                    ////2.插入日志表。
                    SetUserLog("上报变更信息", changeIdsNew.TrimEnd(','), userGuid, userName, areaCode, "3", codeType.ToString());
                    tran.Commit();
                    ////3.填充返回结果。
                    result.Message = "变更申请上报成功";
                    result.Result = true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    //插入日志表
                    SysLogManager.Log(new Sys_Log()
                    {
                        ErrorMessage = ex.Message,
                        LogDate = DateTime.Now
                    });
                    result.Message = "变更上报失败：" + ex.Message;
                    result.Result = false;
                }
                finally
                {
                    con.Close();
                }
            }
            return result;
        }

        /// <summary>
        /// 判断是否存在变更信息记录
        /// </summary>
        /// <param name="empGuid"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckChangeIsExist(string changeId)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            int objeId = 0;
            if (!int.TryParse(changeId, out objeId))
            {
                result.Result = false;
                result.Message = "参数信息不正确！";
                return result;
            }
            ////查询
            var currentChange = dbContext.ChangeSetRecords.Where(m => (m.IsDel == false || m.IsDel == null) && m.Id == objeId).FirstOrDefault();
            if (currentChange == null)
            {
                result.Result = false;
                result.Message = "变更信息不存在！";
                return result;
            }
            result.Result = true;
            result.ReturnValue = currentChange;
            return result;
        }

        /// <summary>
        /// 取得审核状态及操作权限
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="optType"></param>
        /// <param name="codeType"></param>
        /// <param name="roleId"></param>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        private DTO.OperationResult CheckChangeFlowCode(string objectId, int optType, int? codeType,
              string roleId, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            result.Result = true;
            ////取得当前审核状态
            List<Tb_FlowCode_Zbdl> flowCodes = dbContext.FlowCodes.Where(f => f.ObjectId == objectId && f.CodeType == codeType && f.IsDel == false && f.AreaCode == areaCode).ToList();
            if (flowCodes == null || flowCodes.Count == 0)
            {
                ////添加审核状态
                Tb_FlowCode_Zbdl flowCode = ChangeFlowCodeAdd(objectId, codeType, areaCode);
                flowCodes.Add(flowCode);
            }
            Fly.Common.WorkFlow.OptType opt = (Fly.Common.WorkFlow.OptType)System.Enum.Parse(typeof(Fly.Common.WorkFlow.OptType), optType.ToString());////当前操作
            ////返回flowcode操作状态
            foreach (Tb_FlowCode_Zbdl flowCode in flowCodes)
            {
                var result1 = Fly.Common.WorkFlow.FlowHelper.GetNextFlowCode(
                                    roleId, string.Empty,
                                    flowCode.AreaCode,
                                    flowCode.CodeType.ToString(), flowCode.FlowCode, opt);
                result.Result = result1.Result;
                result.Message = result1.Message;
                result.ReturnValue = result1.NextFlowCode;
                if (!result.Result)
                {
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// 添加flowcode
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="codeType"></param>
        /// <param name="areaCode"></param>
        private Tb_FlowCode_Zbdl ChangeFlowCodeAdd(string objectId, int? codeType, string areaCode)
        {
            Tb_FlowCode_Zbdl flowCode = dbContext.FlowCodes.Where(f => f.ObjectId == objectId && f.CodeType == codeType && f.AreaCode == areaCode && f.IsDel == false).FirstOrDefault();
            if (flowCode != null)
            {
                return flowCode;
            }
            flowCode = new Tb_FlowCode_Zbdl();
            flowCode.AreaCode = areaCode;
            flowCode.CodeType = codeType;
            flowCode.FlowCode = "0";
            flowCode.IsDel = false;
            flowCode.ObjectId = objectId;
            flowCode.UpdateTime = DateTime.Now;
            dbContext.FlowCodes.Add(flowCode);
            dbContext.SaveChanges();
            return flowCode;
        }

        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="codeType"></param>
        /// <param name="areaCode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private DTO.OperationResult ChangeFlowCodeEdit(string objectId, int? codeType, string folwCode, string areaCode)
        {
            DTO.OperationResult result = new DTO.OperationResult();
            Tb_FlowCode_Zbdl flowCode = ChangeFlowCodeAdd(objectId, codeType, areaCode);
            flowCode.FlowCode = folwCode;
            flowCode.UpdateTime = DateTime.Now;
            flowCode.Description = "";
            dbContext.SaveChanges();
            result.Result = true;
            return result;
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="empGuid"></param>
        /// <param name="classID"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        private bool SetUserLog(string message, string ObjectId, string IsrtUser, string IsrtUserName, string areaCode, string FunctionType, string codeType)
        {
            LogAndFlowHelper loghelper = new LogAndFlowHelper();
            loghelper.InsertDetailUserLog(message, ObjectId, codeType, FunctionType, new User_Log()
            {
                IsrtDate = DateTime.Now,
                IsrtUserArea = areaCode,
                IsrtUser = IsrtUser,
                IsrtUserName = IsrtUserName,
            });
            return true;
        }

        #endregion

        public override IList<DTO.ChangeDetail> GetChangeSetRecordList(out int cnt,
          int pageNo,
          int pageSize,
          string conditions,
          string areaCode)
        {
            var changeItem = dbContext.ChangeItems;
            var changeSetRecord = dbContext.ChangeSetRecords;
            var changeRecord = dbContext.ChangeRecords;
            var tbFlowCode = dbContext.FlowCodes;
            var query = from setRecord in changeSetRecord
                        join tbflow in tbFlowCode on setRecord.ObjectId equals tbflow.ObjectId into recordflows
                        from recordflow in recordflows.DefaultIfEmpty()
                        where (recordflow.IsDel == null || recordflow.IsDel == false) &&
                        (setRecord.IsDel == null || setRecord.IsDel == false)
                        select new DTO.Tb_ChangeSetRecord
                        {
                            Id = setRecord.Id,
                            ObjectId = setRecord.ObjectId,
                            ObjectName = setRecord.ObjectName,
                            ObjectType = setRecord.ObjectType,
                            IsrtDate = setRecord.IsrtDate,
                            IsrtUserId = setRecord.IsrtUserId,
                            IsrtUserName = setRecord.IsrtUserName,
                            Description = setRecord.Description,
                            CodeType = recordflow.CodeType,
                            FlowCode = recordflow.FlowCode
                        };
            if (!string.IsNullOrEmpty(conditions) && conditions.Count() > 0)
            {
                var condition = JsonConvert.DeserializeObject<IList<DTO.QueryChangeSetInfoCondition>>(conditions);
                query = query.BuildCondition<DTO.Tb_ChangeSetRecord>(condition);
            }
            var iquery = query.ToList().Select(o => new DTO.ChangeDetail
            {
                ChangeSet = new DTO.Tb_ChangeSetRecord
                {
                    Id = o.Id,
                    ObjectId = o.ObjectId,
                    ObjectName = o.ObjectName,
                    ObjectType = o.ObjectType,
                    IsrtDate = o.IsrtDate,
                    IsrtUserId = o.IsrtUserId,
                    IsrtUserName = o.IsrtUserName,
                    Description = o.Description,
                    CodeType = o.CodeType,
                    FlowCode = o.FlowCode
                },
                ChangeInfos = new List<DTO.Tb_ChangeRecord>()
            }
            );
            cnt = iquery.Count();
            iquery = iquery.OrderByDescending(o => o.ChangeSet.Id).Skip((pageNo - 1) * pageSize).Take(pageSize);
            var result = iquery.ToList();
            ////获取变更项
            foreach (var item in result)
            {
                item.ChangeInfos = dbContext.ChangeRecords.Where(c => c.ChangeSetId == item.ChangeSet.Id)
                .Select(o => new DTO.Tb_ChangeRecord
                {
                    ID = o.ID,
                    ClassID = o.ID,
                    EmpGuid = o.EmpGuid,
                    ChangeSetId = o.ChangeSetId,
                    ChangeItem = o.ChangeItem,
                    ChangeItemName = o.ChangeItemName,
                    BeforeChange = o.BeforeChange,
                    BeforeValue = o.BeforeValue,
                    AfterChange = o.AfterChange,
                    AfterValue = o.AfterValue,
                    Remark = o.Remark,
                    OptDate = o.OptDate,
                    ClassValue = o.ClassValue,
                    ChangeItemSubCode = o.ChangeItemSubCode
                }).ToList();
            }
            return result;
        }

        #region 获取条款

        DAL.LcDAL.BasicDAL BasicDAL = new DAL.LcDAL.BasicDAL();

        /// <summary>
        /// 条款查询
        /// </summary>
        /// <param name="bKind"></param>
        /// <param name="bType"></param>
        /// <param name="Areacode"></param>
        /// <param name="condtion"></param>
        /// <returns></returns>
        public override string GetEScoreType(int bKind, int bType, string Areacode, string condtion)
        {
            IList<e_ScoreType_zbdl> list = BasicDAL.GetEScoreType(bKind, bType, Areacode, condtion);
            return JsonConvert.SerializeObject(list);
        }

        public override DTO.ScoreItem Gete_ScoreTypeByTypeID(int typeid)
        {
            var query = from score in dbContext.Score_zbdl
                        join scoreType in dbContext.ScoreType_zbdl
                        on score.TypeID equals scoreType.ID
                        where score.TypeID == typeid
                        select new DTO.ScoreItem
                        {
                            ScoreID = score.ID,
                            ScoreTypeID = scoreType.ID,
                            ScoreTitle = score.Title,
                            ScoreTypeTitle = scoreType.Title,
                            TypeID = score.TypeID
                        };

            return query.FirstOrDefault();
        }

        /// <summary>
        /// 子条款查询
        /// </summary>
        /// <param name="typeID"></param>
        /// <param name="condtion"></param>
        /// <returns></returns>
        public override string GetEScore(int typeID, string condtion)
        {
            IList<e_Score_zbdl> list = BasicDAL.GetEScore(typeID, condtion);
            return JsonConvert.SerializeObject(list);
        }
        #endregion
    }
}
